我需要将包含十六进制值作为字符的字符串转换为字节数组。虽然这已经作为第一个答案在这里得到了回答,但我收到以下错误:
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);
}