0. 在openEuler(推荐)或Ubuntu或Windows(不推荐)中完成下面任务
1 参考《GMT 0009-2012 SM2密码算法使用规范》第6节“数据转换” 在utils.h和utils.c中完成整数与8位字节串的转换功能(10'):
int Int2ByteArr(unsigned int i, unsigned char * ba);
int ByteArr2Int(unsigned char * ba,unsigned int * i);
2 并写出测试代码测试上述函数(不能与下面代码一样),比如(10'):
unsigned int i=123456789;
Int2ByteArr(i, ba);
//结果:ba = {0x07,0x5B,0xCD,0x15};
unsigned char ba [] = {0x07,0x5B,0xCD,0x15};
ByteArr2Int(ba, &i);
//结果: i=123456789
3 提交代码(或代码链接)和运行结果
//main.c
#include<stdio.h>
#include"utils.h"
int main(){
int a;
char bytearr[100];
printf("input an int:");
scanf("%d",&a);
INT2ByteArr(a,bytearr);
printf("ByteArr is: %s\n",bytearr);
char barr[100];
int h;
printf("input bytearr:");
scanf("%s",barr);
ByteArr2INT(barr,&h);
printf("int is: %d\n",h);
}
//utils.c
#include<stdio.h>
#include"utils.h"
#include<string.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("error");
}
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("error");
}
return 0;
}
int INT2ByteArr(int i,char *ba){
int j;
int a;
int sum=0;
int k=i;
for(j=0;;j++)
{
k=k/16;
if(k!=0)
sum++;
else
break;
}
for(j=sum;j>=0;j--){
a = i%16;
Hex2Char(a,&ba[j]);
i=i/16;
}
ba[sum+1]='\0';
}
int ByteArr2INT(char *ba,int *i)
{
int len;
int j;
int n=0;
*i=0;
len = strlen(ba);
for(j=0;j<len;j++)
{
Char2Hex(ba[j],&n);
//printf("%d\n",n);
*i=(*i)*16+n;
}
}