我需要将包含十六进制值作为字符的字符串转换为字节数组。虽然这已经得到回答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/