标签:ba int bs ByteArr2Bitstr char 数组 位串 include 字节
一、任务详情
- 在openEuler(推荐)或Ubuntu或Windows(不推荐)中完成下面任务
1 参考《GMT 0009-2012 SM2密码算法使用规范》第6节“数据转换” 在utils.h和utils.c中完成位串与8位字节串的转换功能(10'):
int Bitstr2ByteArr(unsigned char * bs, unsigned char * ba,int *lba);
int ByteArr2Bitstr(unsigned char * ba, unsigned char * bs, int *lbs);
2 并写出测试代码测试上述函数(不能与下面代码一样),比如(10'):
unsigned char bs [] = "1010010100011100";
int len;
Bitstr2ByteArr(bs, char * ba, &len);
//结果:ba = {0x5, 0x1C}; len=2
char ba[] = {0x5, 0x1C}
ByteArr2Bitstr(char * ba, char * bs);
//结果:bs= "1010010100011100"
3 提交代码(或代码链接)和运行结果
主函数main1.c
#include <stdio.h>
#include <string.h>
#include "utils.h"
int main(){
int bitList[8] = { 0 };
int a;
sscanf("32", "%x", &a);
ByteArr2Bitstr(a, bitList);
printf("0x32 be changed to\n");
for (int i =0 ;i<8;++i)
printf("%i",bitList[i]);//八位长
printf("\n");
int b,n;
n=Bitstr2ByteArr(bitList,b);
printf("the data will be changed to\n");
printf("%x\n",n);
}
~
utils1.c
#include <stdio.h>
#include <string.h>
#include "utils.h"
//20191223
int ByteArr2Bitstr(int ba,int * bs){
for (int i =0 ;i<8;++i)
{
int nTmp = (1 << i);
bs[7-i] = (( ba & nTmp) == nTmp )? 1 : 0;
}
}
int Bitstr2ByteArr(int * bs,int ba)
{
int n = 0;
for (int i = 0 ; i < 8;++i)
{
n += bs[7-i] * (1 << i);
}
*bs = n;
return n;
}
头文件utils1.h
#ifndef _UTILS_H_
#define _UTILS_H_
int ByteArr2Bitstr(int ba,int * bs);
int Bitstr2ByteArr(int * bs,int ba);
#endif
编译指令
gcc test/main1.c src/utils1.c -o bin/20191223test2 -Iinclude
运行结果
标签:ba,int,bs,ByteArr2Bitstr,char,数组,位串,include,字节 来源: https://www.cnblogs.com/zzjjyy123/p/16337621.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。