-
在openEuler(推荐)或Ubuntu或Windows(不推荐)中完成下面任务
-
在附件中的utils.h和utils.c中完成16进制字符'0'-'9','A'-'F','a'-'f'与十六进制数据0-15的转换功能(10’):
int Hex2Char(unsigned int fromi,unsigned char * toc);
int Char2Hex(unsigned char fromc,unsigned int * toi);
- 并写出测试代码测试上述函数(不能与下面代码一样),比如:(10’)
unsigned char c;
Hex2Char(1, &c)
//结果:c = '1'
Hex2Char(15, &c)
//结果:c = 'F'
unsigned int i;
Char2Hex('1', &i);
//结果:i = 1
Char2Hex('F', &i);
//结果:i = 15
- 提交代码(或代码链接)和运行结果
uitls.h
#ifndef _UTIL_H_
#define _UTIL_H_
//char Hex2Char(int i);
//int Char2Hex(char c);
int Hex2Char(int fromi,char * toc);
int Char2Hex(char fromc,int * toi);
int Bitstr2ByteArr(char * bs,char * ba);
int ByteArr2Bitstr(char * ba,char * bs);
int Int2ByteArr(int i,char * ba);
int ByteArr2Int(char * ba,int * i);
#endif
utils.c
#include<stdio.h>
#include"utils.h"
char Hstr[] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
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;
}
main.c
#include<stdio.h>
#include"utils.h"
int main(){
int n1,n2;
char c1,c2;
printf("请输入一个0~15的数:");
scanf("%d",&n1);
Hex2Char(n1,&c1);
printf("对应的16进制字符是%c\n",c1);
printf("请输入一个16进制字符:");
scanf("%s",&c2);
Char2Hex(c2,&n2);
printf("%c对应的数是%d\n",c2,n2);
}
运行截图: