c - 如何正确地将十六进制字符串转换为 C 中的字节数组?

标签 c arrays type-conversion

我需要将包含十六进制值作为字符的字符串转换为字节数组。虽然这已经得到回答already here作为第一个答案,我收到以下错误:

warning: ISO C90 does not support the ‘hh’ gnu_scanf length modifier [-Wformat]

因为我不喜欢警告,省略 hh 只会产生另一个警告

warning: format ‘%x’ expects argument of type ‘unsigned int *’, but argument 3 has type ‘unsigned char *’ [-Wformat]

我的问题是:如何正确执行此操作?为了完成,我在这里再次发布示例代码:

#include <stdio.h>

int main(int argc, char **argv)
{
    const char hexstring[] = "deadbeef10203040b00b1e50", *pos = hexstring;
    unsigned char val[12];
    size_t count = 0;

     /* WARNING: no sanitization or error-checking whatsoever */
    for(count = 0; count < sizeof(val)/sizeof(val[0]); count++) {
        sscanf(pos, "%2hhx", &val[count]);
        pos += 2 * sizeof(char);
    }

    printf("0x");
    for(count = 0; count < sizeof(val)/sizeof(val[0]); count++)
        printf("%02x", val[count]);
    printf("\n");

    return(0);
}

最佳答案

您可以改用 strtol()

只需替换这一行:

sscanf(pos, "%2hhx", &val[count]);

与:

char buf[10];
sprintf(buf, "0x%c%c", pos[0], pos[1]);
val[count] = strtol(buf, NULL, 0);

更新:您可以避免使用 sprintf(),而是使用此代码段:

char buf[5] = {"0", "x", pos[0], pos[1], 0};
val[count] = strtol(buf, NULL, 0);

关于c - 如何正确地将十六进制字符串转换为 C 中的字节数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18267803/

相关文章:

javascript - 重置 v-model 而不更新其因变量

ios - 如何在 Swift 中为 Int 数组(自定义字符串结构)实现 Hashable 协议(protocol)

c++ - 需要帮助创建数组并在另一个函数中编辑它并将其发送回初始函数

c++ - 从类类型到类类型的隐式转换

c - C 中的指针整数字符警告

c - 正确输入和验证十六进制值

c - 在不知道结构大小的情况下在结构中声明二维数组?

c# - 当值可以为空时如何使用 Convert.ChangeType(value, type)

c - 在纯 C 中打印 void 类型

c - 如何返回第三个结构中两个结构值之间的差异?