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

Ale*_*lex 5 c arrays type-conversion

我需要将包含十六进制值作为字符的字符串转换为字节数组。尽管这里已经作为第一个答案已经回答了,但出现以下错误:

warning: ISO C90 does not support the ‘hh’ gnu_scanf length modifier [-Wformat]
Run Code Online (Sandbox Code Playgroud)

由于我不喜欢警告,因此遗漏hh只会产生另一个警告

warning: format ‘%x’ expects argument of type ‘unsigned int *’, but argument 3 has type ‘unsigned char *’ [-Wformat]
Run Code Online (Sandbox Code Playgroud)

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

#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);
}
Run Code Online (Sandbox Code Playgroud)

mvp*_*mvp 4

你可以用strtol()它代替。

只需替换这一行:

sscanf(pos, "%2hhx", &val[count]);
Run Code Online (Sandbox Code Playgroud)

和:

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

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

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

  • 您可以传递 16 作为“strtol”的第三个参数,而不是前缀“0x”。 (4认同)