gpt4 book ai didi

c++ - 如何转换一个char表示的十六进制值?

转载 作者:行者123 更新时间:2023-11-28 01:48:25 24 4
gpt4 key购买 nike

我有一个无符号字符数组,我想将它的前四个元素解析为十六进制值。

我收到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[]的前四个元素的十六进制值

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

提前致谢。

最佳答案

您可以从十六进制数字中获取整数值(其中十六进制数字是此集合中的任何字符: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 a[] = "abcd",您将得到每个字符的 {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

关于c++ - 如何转换一个char表示的十六进制值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43924528/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com