【发布时间】:2013-08-18 12:50:03
【问题描述】:
我需要将包含十六进制值作为字符的字符串转换为字节数组。尽管已将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,这可能会有所帮助 -
没有什么是额外变量解决不了的。
标签: c arrays type-conversion