数据转换-16进制字符

题目要求:
0. 在openEuler(推荐)或Ubuntu或Windows(不推荐)中完成下面任务: 1. 在utils.h和utils.c中完成16进制字符'0'-'9','A'-'F','a'-'f'与十六进制数据0-15的转换功能: int Hex2Char(unsigned int fromi,unsigned char * toc); int Char2Hex(unsigned char fromc,unsigned int * toi); 2. 并写出测试代码测试上述函数(不能与下面代码一样),比如: 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 3. 提交代码(或代码链接)和运行结果
代码:

#include <stdio.h>

 

 

char Hex2Char(int i){

if(i>=0 && i<=9)
return i + 0x30;
if(i==10 && i<15)
return i + 0x37;
}

int Char2Hex(char fromc){
if(fromc >= 'a' && fromc < 'g')
return (int) (fromc-'a')+10;
else if(fromc >= 'A' && fromc < 'G')
return (int)(fromc-'A')+10;
else if(fromc >= 0 && fromc <= 9)
return (int) fromc;
else
return -1;
}

int ByteArr2Bitstr(int ba,int * bs){
int i,nTmp;
for (i =0 ;i<8;++i)
{
nTmp = (1 << i);
bs[7-i] = (( ba & nTmp) == nTmp )? 1 : 0;
}
}

int Bitstr2ByteArr(int * bs,int ba)
{
int n = 0;
int i;
for (i = 0 ; i < 8;++i)
{
n += bs[7-i] * (1 << i);
}
*bs = n;
return n;
}

int main(){
/*printf("%c\n",Hex2Char(10));
printf("%i\n",Char2Hex('a'));*/
int bitList[8] = { 0 };
int a;
int i;
sscanf("13", "%x", &a);
ByteArr2Bitstr(a, bitList);
for ( i =0 ;i<8;++i)
printf("%i",bitList[i]);
printf("\n");
int b,n;
n=Bitstr2ByteArr(bitList,b);
printf("%x\n",n);
}


运行结果:

 

 



posted @ 2021-05-09 20:22  Acmer_xsh  阅读(150)  评论(0编辑  收藏  举报