在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 = "075BCD15";
unsigned char ba [] = "075BCD15";
ByteArr2Int(ba, &i);
//结果: i=123456789
3 提交代码(或代码链接)和运行结果
utils.h
#ifndef UTILS_H
#define UTILS_H
int Int2ByteArr(unsigned int i, unsigned char * ba);
int ByteArr2Int(unsigned char * ba,unsigned int * i);
#endif
main.c
#include<stdio.h>
#include"utils.h"
int main(){
unsigned int i=20201205;
unsigned char ba [100];
Int2ByteArr(i, ba);
printf("ba=%s\n",ba);
unsigned char bb [] = "75DDFA05";
unsigned int h;
ByteArr2Int(bb, &h);
printf("%d\n",h);
}
utils.c
#include<stdio.h>
#include"utils.h"
#include<string.h>
int Hex2Char(int f,char *t)
{
if(f>=0&&f<=9)
{
*t= f+'0';
}
else if(f>=10&&f<=15)
{
*t = f+'A'-10;
}
else
{
printf("input error!");
}
}
int Char2Hex(char f,int *t1)
{
if(f>='0'&& f<='9')
{
*t1= f-'0';
}
else if(f>='A'&& f<='F')
{
*t1= f-'A'+10;
}
else
{
printf("input error!");
}
}
int Int2ByteArr(unsigned int i, unsigned 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(unsigned char * ba,unsigned int * i)
{
int len;
int j;
int n=0;
*i=0;
len = strlen(ba);
for(j=0;j<len;j++)
{
Char2Hex(ba[j],&n);
*i=(*i)*16+n;
}
}
运行截图: