如何使用2个字符形成ASCII(十六进制)数字

How to form an ASCII(Hex) number using 2 Chars?

本文关键字:十六进制 数字 ASCII 何使用 2个 字符      更新时间:2023-10-16

我有字符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字符。