如何在 C 中正确地将十六进制字符串转换为字节数组?
问题描述:
我需要将包含十六进制值作为字符的字符串转换为字节数组.虽然这已经被回答已经在这里作为第一个答案,我得到以下错误:
I need to convert a string, containing hex values as characters, into a byte array. Although this has been answered already here as the first answer, I get the following error:
warning: ISO C90 does not support the ‘hh’ gnu_scanf length modifier [-Wformat]
因为我不喜欢警告,省略hh
只会产生另一个警告
Since I do not like warnings, and the omission of hh
just creates another warning
warning: format ‘%x’ expects argument of type ‘unsigned int *’, but argument 3 has type ‘unsigned char *’ [-Wformat]
我的问题是:如何正确地做到这一点?为了完成,我再次在此处发布示例代码:
my question is: How to do this right? For completion, I post the example code here again:
#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);
UPDATE:您可以避免使用 sprintf()
而使用此代码段:
UPDATE: You can avoid using sprintf()
using this snippet instead:
char buf[5] = {"0", "x", pos[0], pos[1], 0};
val[count] = strtol(buf, NULL, 0);