C++中ASCII码和HEX十六进制的相互转换
把ASCII字符转换成数值,
unsigned char ascii2value(unsigned char c)
{
if ('0' <= c && c <= '9')
return c - '0';
else if ('a' <= c && c <= 'f')
return c - 'a' + 10;
else if ('A' <= c && c <= 'F')
return c - 'A' + 10;
else abort();
}
与之相反,把16进制值转换成ASCII字符的函数如下,
unsigned char val2char(unsigned char c)
{
if (0<=c && c<=9)
return c + '0';
else if (10 <= c && c <= 15)
return c-10 + 'A';
else abort();
}
使用举例:
把一个HEX串0xXX 0xXX以字符的形式输出
std::string HexToAscii(char* inBuf, int numBytes) {
int len = numBytes<<1;
unsigned char cch = 0, lch=0, uch=0;
std::string str;
for (int i = 0; i < numBytes; i += 1)
{
cch = *inBuf++;
uch = val2char((cch & 0xF0) >> 4);
lch = val2char(cch & 0x0F);
str.append("0x");
str.push_back(uch);
str.push_back(lch);
str.append(" ");
}
return str;
}
比如, char[2]={0xAB, 0xAC},
HexToAscii(char, 2)返回的就是字符串“0xAB 0xAC"。