我想在c中将十六进制值转换为字符串。 例如:
a[4] = {0x34, 0x31, 0xF5, 0x43}
需要转换为字符串
b[8] = {3431F543}
答案 0 :(得分:1)
DevSolar的sprintf解决方案简单易用。但我已经提出了更优化的黑客版本。
void convert_hex_4b_to_string(char buf[9], int ar[4])
{
static const char tbl[] = "0123456789ABCDEF";
buf[0] = tbl[((unsigned)ar[0] >> 4) & 0x0f];
buf[1] = tbl[((unsigned)ar[0]) & 0x0f];
buf[2] = tbl[((unsigned)ar[1] >> 4) & 0x0f];
buf[3] = tbl[((unsigned)ar[1]) & 0x0f];
buf[4] = tbl[((unsigned)ar[2] >> 4) & 0x0f];
buf[5] = tbl[((unsigned)ar[2]) & 0x0f];
buf[6] = tbl[((unsigned)ar[3] >> 4) & 0x0f];
buf[7] = tbl[((unsigned)ar[3]) & 0x0f];
buf[8] = '\0';
}
...假设所有整数都小于0x100。