数据转换-位串字节数组
作者:互联网
一、任务详情
- 在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