C语言 十六进制字符转换为字符串

我们知道,当在进行设备通信(eg:串口)的时候,通信数据都是16进制字符,如果需要记录日志,16进制字符是无法直接写入文本的(乱码),这是就需要将16进制字符转换为字符串


方法如下:

#include

unsigned char  s_des[100] = {0};
int length  = 9;
unsigned char s_src[length]  =  {0xFE,0x01,0x52,0xFF,0xEF,0xBA,0x35,0x90,0xFA};


unsigned char IntToHexChar(unsigned char c)
{
if (c > 9)
return (c + 55);
else
return (c + 0x30);
}




int main()
{
unsigned char temp;
int i;
for (i=0; i{
temp = s_src[i]&0xf0;
s_des[2*i] = IntToHexChar(temp >> 4);
temp = s_src[i]&0x0f;
s_des[2*i+1] = IntToHexChar(temp);
}
printf("*** %s ***\n",s_des);
return 0;
}


你可能感兴趣的:(C语言 十六进制字符转换为字符串)