数据转换-位串字节数组
- 在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 提交代码(或代码链接)和运行结果
head.h
#define UTILS_H
int Bitstr2ByteArr(unsigned char *bs, unsigned char *ba, int *lba);
int ByteArr2Bitstr(unsigned char *ba, unsigned char *bs, int *lbs);
#endif // UTILS_H
utils.c
#include <string.h>
#include <stdlib.h>
#include "utils.h"
int Bitstr2ByteArr(unsigned char *bs, unsigned char *ba, int *lba) {
int len = strlen((char *)bs);
*lba = (len + 1) / 2;
for (int i = 0; i < *lba; i++) {
int high = bs[i * 2] - '0' * (bs[i * 2] >= '0' && bs[i * 2] <= '9') - 'A' * (bs[i * 2] >= 'A' && bs[i * 2] <= 'F') + 10;
int low = bs[i * 2 + 1] - '0' * (bs[i * 2 + 1] >= '0' && bs[i * 2 + 1] <= '9') - 'A' * (bs[i * 2 + 1] >= 'A' && bs[i * 2 + 1] <= 'F') + 10;
ba[i] = (high << 4) + low;
}
return 0;
}
int ByteArr2Bitstr(unsigned char *ba, unsigned char *bs, int *lbs) {
int len = *lbs * 2;
for (int i = 0; i < *lbs; i++) {
int high = (ba[i] >> 4) & 0x0F;
int low = ba[i] & 0x0F;
bs[i * 2] = high + '0' * (high >= 0 && high <= 9) + ('A' - 10) * (high >= 10 && high <= 15);
bs[i * 2 + 1] = low + '0' * (low >= 0 && low <= 9) + ('A' - 10) * (low >= 10 && low <= 15);
}
bs[len] = '\0';
return 0;
}
main.c
#include <stdio.h>
#include "utils.h"
int main() {
unsigned char bs[] = "1010010100011100";
unsigned char ba[1024];
int len;
int i;
Bitstr2ByteArr(bs, ba, &len);
printf("Bitstr2ByteArr 转换结果:");
for ( i = 0; i < len; i++) {
printf("%02X", ba[i]);
}
printf("\n");
unsigned char ba2[] = {0x05, 0x1C};
int lbs = 2;
unsigned char bs2[1024];
ByteArr2Bitstr(ba2, bs2, &lbs);
printf("ByteArr2Bitstr 转换结果:%s\n", bs2);
return 0;
}
运行截图: