- 在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 = “051C”; len=2
char ba[] = "051C";
ByteArr2Bitstr(char * ba, char * bs);
//结果:bs= "1010010100011100"
3 提交代码(或代码链接)和运行结果
main.c
#include <stdio.h>
#include <string.h>
#include "utils.h"
int main(){
int bitList[8] = { 0 };
int a;
sscanf("20191227", "%x", &a);
ByteArr2Bitstr(a, bitList);
printf("0x20191227 be changed to\n");
for (int i =0 ;i<32;++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);
}
utils.c
#include <stdio.h>
#include <string.h>
#include "utils.h"
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;
}
utils.h
#ifndef _UTILS_H_
#define _UTILS_H_
int ByteArr2Bitstr(int ba,int * bs);
int Bitstr2ByteArr(int * bs,int ba);
#endif
截图: