如何使用2个字符形成ASCII(十六进制)数字
How to form an ASCII(Hex) number using 2 Chars?
我有字符byte[0] = '1' (H'0x31)
和byte[1] = 'C'(H'0x43)
我正在使用一个缓冲区来更多地缓冲char hex_buff[0]
。我想在这个hex_buff[0] = 0x1C
中有十六进制内容(即字节[0]和字节[1]的组合)
我使用了下面的代码,但我意识到我的代码只适用于十六进制值0-9的
char s_nibble1 = (byte[0]<< 4)& 0xf0;
char s_nibble2 = byte[1]& 0x0f;
hex_buff[0] = s_nibble1 | s_nibble2;
//这里我想要0x1C
而不是0x13
是什么阻止您使用strtol()
?
char bytes[] = "1C";
char buff[1];
buff[0] = strtol(bytes, NULL, 16); /* Sets buff[0] to 0x1c aka 28. */
按照chux的注释添加:strtol()
仅对以0
结尾的字符数组进行操作。OP的问题不一定是这样。
一种可能的方法,不依赖于其他字符操作函数:
char hex2byte(char *hs)
{
char b = 0;
char nibbles[2];
int i;
for (i = 0; i < 2; i++) {
if ((hs[i] >= '0') && (hs[i] <= '9'))
nibbles[i] = hs[i]-'0';
else if ((hs[i] >= 'A') && (hs[i] <= 'F'))
nibbles[i] = (hs[i]-'A')+10;
else if ((hs[i] >= 'a') && (hs[i] <= 'f'))
nibbles[i] = (hs[i]-'a')+10;
else
return 0;
}
b = (nibbles[0] << 4) | nibbles[1];
return b;
}
例如:hex2byte("a1")
返回字节0xa1
。
在您的情况下,应该将函数调用为:hex_buff[0] = hex2byte(byte)
。
您试图通过屏蔽字符代码的位来获得半字节,而不是减去实际值。这是行不通的,因为范围是断开的:在编码中,[0..9]
和[A-F]
之间有一个间隙,所以掩蔽将失败。
你可以通过添加一个小的助手函数来解决这个问题,并在你的代码中使用两次:
int hexDigit(char c) {
c = toupper(c); // Allow mixed-case letters
switch(c) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9': return c-'0';
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F': return c-'A'+10;
default: // Report an error
}
return -1;
}
现在你可以这样编码你的转换:
int val = (hexDigit(byte[0]) << 4) | hexDigit(byte[1]);
看起来您正在尝试将ASCII十六进制转换为内部表示。
有很多方法可以做到这一点,但我最常用的方法是:
int nibval(unsigned short x)
{
if (('0' <= x) && ('9' >= x))
{
return x - '0';
}
if (('a' <= x) && ('f' >= x))
{
return x - ('a' - 10);
}
if (('A' <= x) && ('F' >= x))
{
return x - ('A' - 10);
}
// Invalid input
return -1;
}
这使用了一个无符号int参数,这样它既适用于单字节字符,也适用于wchar_t字符。
相关文章:
- 从char阵列中提取十六进制数字
- 如何在 c++ 中将十六进制数字转换为字符
- 使用字符串格式限制十六进制数字的数量
- 从输入中找到连续十六进制数字的最大数量
- 将十六进制数字从无符号字符转换为字符串
- 从 bin 文件 -c++ 中读取十六进制数字为每个字符 2 位数字
- 重载输出运算符给出十六进制数字而不是字符串
- 将十六进制数的 char[] 转换为对应于 ASCII 表中十六进制数字的字母的 char[] 并反转
- 从包含十六进制数字的std::string或QString创建std::bitset或QBitArray
- "first-chance exception..."消息中的十六进制数字是什么意思?
- 一次打印 2 个字节的十六进制数字
- 连接两个十六进制数字
- 分析64位十六进制数字
- 在一行代码中输入2个十六进制数字和一个字符串
- 十六进制数字系统中的指针值
- 将std::字符串数字转换为十六进制数字
- 格式化带符号十六进制数字的输出
- 如何使用stringstream格式化十六进制数字
- string控制字符:将十六进制数字赋给字符串
- 同时向QByteArray添加多个十六进制数字