从无符号字符生成十六进制

make in hex from unsigned char

假设我有一段代码像

unsigned char *tag = NULL;
tag = (unsigned char *)malloc(8);
memset(tag, 0, 8);
memcpy(tag, (const char *)"50C59390",8);

我必须将它作为长度 4 发送。所以我试图将它转换为 4 字节十六进制,如 0x50C59390。

unsigned char * buffer = (unsigned char *)calloc(4, sizeof(char));
int index,j = 0;
for(index = 0 ; index < 8; index++)
{        
    buffer[j] = (tag[index] & 0x0F) | (tag[++index]>>4 & 0xF0);
    printf("%02X", buffer[j]);
    j++;
}

我正在尝试上面的代码。但它没有按要求工作。

根据你的问题,我不确定你是否尝试转换为字符串或从字符串转换。但是,如果您有 C++11 可用,则可以使用 std::stoi() and std::to_string() 进行简单转换:

int hex_value = std::stoi(tag, nullptr, 16)

请注意 std::stoi() 的第三个参数如何表示基数(在本例中 16 表示十六进制)。

您不能只将 ascii 字符复制为十六进制值。你需要转换它们。

类似于:

unsigned char convert(unsigned char ch)
{
    if (ch >= '0' && ch <= '9')
    {
        return ch -'0';
    }

    if (ch >= 'a' && ch <= 'f')
    {
        return ch -'a' + 10;
    }

    if (ch >= 'A' && ch <= 'F')
    {
        return ch -'A' + 10;
    }

    return 0; // or some error handling
}

并像这样使用它:

for(index = 0 ; index < 8; index = index + 2)
{   
    buffer[j] = convert(tag[index]) << 4;
    buffer[j] += convert(tag[index+1]);

    printf("%02X", buffer[j]);
    j++;
}

在此处在线查看:https://ideone.com/e2FPCT