如何转换char表示的十六进制值?

时间:2017-05-11 20:00:19

标签: c++ hex

我有一个unsigned char数组,我希望将前四个元素解析为HEX值。

我收到了unsiged char array a[],其内容是

for (int i = 0; i < l; i++) {
  SerialUSB.print(" Index : ");
  SerialUSB.print(i);
  SerialUSB.print(" ,Unsigned Char ");
  SerialUSB.print( a[i]);
  SerialUSB.print(", CHAR ");
  SerialUSB.print( (char) a[i]);
  SerialUSB.println();
}

Index:0  ,Unsigned Char 98, CHAR b
Index:1  ,Unsigned Char 49, CHAR 1
Index:2  ,Unsigned Char 53, CHAR 5
Index:3  ,Unsigned Char 57, CHAR 9
Index:4  ,Unsigned Char 55, CHAR 7
Index:5  ,Unsigned Char 56, CHAR 8
Index:6  ,Unsigned Char 85, CHAR U
Index:7  ,Unsigned Char 55, CHAR 7
Index:8  ,Unsigned Char 56, CHAR 8
Index:9  ,Unsigned Char 85, CHAR U
Index:10 ,Unsigned Char 55, CHAR 7
Index:11 ,Unsigned Char 56, CHAR 8
Index:12 ,Unsigned Char 85, CHAR U

如何获取数组a[]

的前四个元素的HEX值
inHex[0] = 0xB; // 0xB = 11
inHex[1] = 0x15; // which should come from having concatenated the values `a[1]= '1'` algong with `a[2]='2'`
inHex[3] = 0x9; // which should  be the char value of a[3] in HEX

提前致谢。

1 个答案:

答案 0 :(得分:2)

您可以从十六进制数字中获取整数值(其中十六进制数字是此集合中的任何字符:0123456789abcdefABCDEF):

int fromHex(char c)
{
    if (c>='0' && c<='9')
        return c-'0';
    if (c>='a' && c<='f')
        return 10+(c-'a');
    if (c>='A' && c<='F')
        return 10+(c-'A');
    return -1; // unexpected char
}

这样,如果你有char [] =&#34; abcd&#34;,你就会得到{11,11,12,14}每个字符。

然后从你的前4个字符中获取整数:

inHex[0] = fromHex(a[0]);
inHex[1] = fromHex(a[1]) * 16 + fromHex(a[2]);
inHex[2] = fromHex(a[3]);

Sample code

#include <stdio.h>

int fromHex(char c)
{
    if (c >= '0' && c <= '9')
        return c - '0';
    if (c >= 'a' && c <= 'f')
        return 10 + (c - 'a');
    if (c >= 'A' && c <= 'F')
        return 10 + (c - 'A');
    return -1; // unexpected char
}

int main()
{
    char a[] = "b159";
    int inHex[3];
    inHex[0] = fromHex(a[0]);
    inHex[1] = fromHex(a[1]) * 16 + fromHex(a[2]);
    inHex[2] = fromHex(a[3]);
    printf("%d %d %d\n", inHex[0], inHex[1], inHex[2]);
    printf("0x%x 0x%x 0x%x\n", inHex[0], inHex[1], inHex[2]);
}

输出:

11 21 9
0xb 0x15 0x9