任务详情
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 提交代码(或代码链接)和运行结果
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);
int Int2ByteArr(unsigned int i,unsigned char *ba);
int ByteArr2Int(unsigned char *ba,unsigned int *i);
#endif
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("输入的十六进制数据不正确!");
}
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 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;
}
}
main.c
#include<stdio.h>
#include"utils.h"
int main(){
//把整型数字转化为字节数组
int p;
char bytearr[100];
printf("Please input an integer\n");
scanf("%d",&p);
printf("integer to ByteArr\n");
INT2ByteArr(p,bytearr);
printf("ByteArr is: %s\n",bytearr);
//把字节数组转化为整型数字
char barr[100];
int h;
printf("Please input ByteArr:");
scanf("%s",barr);
printf("ByteArr to integer:");
ByteArr2INT(barr,&h);
printf("integer is: %d\n",h);
}
运行结果