将十六进制数组转换为字符串

将16进制的数据改为字符串,也就是0xAB,改成“AB”,设数据类型是uint8_t,其实就是unsigned char ,说到底还是个char,要求将0xAB表示成 "AB"字符串类型,字符串在C语言中已字符数组形式存在,即"AB"改为'A' 和'B’ 占用两个char空间。

#include 
#include 

const unsigned char Num2CharTable[16] = "0123456789ABCDEF";

void HexArrayToString(unsigned char *hexarray,int length,unsigned char *string)
{
    int i = 0;
	while(i < length)
	{
	    *(string++) = Num2CharTable[(hexarray[i] >> 4) & 0x0f];
		*(string++) = Num2CharTable[hexarray[i] & 0x0f];
		i++;
	}
	*string = 0x0;
}
int main(void)
{
	unsigned char *str,i;
    unsigned char ch[5] = {0x65,0x43,0x21,0xBA,0xDC};
	HexArrayToString(ch,5,str);
	
	printf("%s\n",str);
    printf("\n");
	for(i = 0; i < 10; i++)
	    printf("%c\n",str[i]);
	
	return 0;
}


执行结果:
654321BADC

6
5
4
3
2
1
B
A
D
C

 

你可能感兴趣的:(C语言)