任务详情
0. 在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 提交代码(或代码链接)和运行结果
utils.h
#ifndef UTILS_H
#define UTILS_H
int Hex2Char(int fromi,char * toc);
int Char2Hex(char fromc,int * toi);
int Bitstr2ByteArr(unsigned char * bs,unsigned char * ba,int *lba);
int ByteArr2Bitstr(unsigned char * ba,unsigned char * bs,int *lbs);
#endif
utils.c
#include<stdio.h>
#include<string.h>
#include"utils.h"
int Hex2Char(int fromi,char *toc)
{
if(fromi>=0&&fromi<=9)
{
*toc= fromi+'0';
}
else if(fromi>=10&&fromi<=15)
{
*toc = fromi+'A'-10;
}
else
{
printf("不在范围内!");
}
return 0;
}
int Char2Hex(char fromc,int *toi)
{
if(fromc>='0'&& fromc<='9')
{
*toi= fromc-'0';
}
else if(fromc>='A'&& fromc<='F')
{
*toi= fromc-'A'+10;
}
else{
printf("不在范围内");
}
return 0;
}
int ByteArr2Bitstr(unsigned char *ba,unsigned char *bs,int *lba)
{
int i,j,L,k,a;
*lba = strlen(ba);
L = *lba;
for(j=0;j<L;j++)
{
Char2Hex(ba[j],&a);
for(i=0;i<4;i++)
{
bs[3*(j+1)-i+j] = a%2+'0';
a=a/2;
}
}
bs[4*L]='\0';
}
int Bitstr2ByteArr(unsigned char *bs,unsigned char *ba,int *lbs)
{
int i,k,j,L;
*lbs = strlen(bs);
L = *lbs;
char string[100];int sum=0;
if(L%4==1)
{
strcpy(string,"000");
strcat(string,bs);
k=L/4+1;
}
else if(L%4==2)
{
strcpy(string,"00");
strcat(string,bs);
k=L/4+1;
}
else if(L%4==3)
{
strcpy(string,"0");;
strcat(string,bs);
k=L/4+1;
}
else
{
k=L/4;
strcpy(string,bs);
}
for(i=0;i<k;i++)
{
for(j=0;j<4;j++)
{
sum=sum*2;
sum=sum+(string[4*i+j]-'0');
}
Hex2Char(sum,&ba[i]);
sum=0;
}
ba[i]='\0';
}
main.c
#include<stdio.h>
#include"utils.h"
int main(){
char ba[100];
char bs[100];
int *lbs;
printf("input ByteArr:\n");
scanf("%s",ba);
ByteArr2Bitstr(ba,bs,lbs);
printf("bitstr:\n");
printf("%s\n",bs);
char ba1[100];
char bs1[100];
int *lba;
printf("input bitstr:\n");
scanf("%s",bs1);
Bitstr2ByteArr(bs1,ba1,lba);
printf("ByteArr:\n");
printf("%s\n",ba1);
return 0;
}
运行结果