How to correctly convert a Hex String to Byte Array in C? -
i need convert string, containing hex values characters, byte array. although has been answered already here first answer, following error:
warning: iso c90 not support ‘hh’ gnu_scanf length modifier [-wformat]
since not warnings, , omission of hh
creates warning
warning: format ‘%x’ expects argument of type ‘unsigned int *’, argument 3 has type ‘unsigned char *’ [-wformat]
my question is: how right? completion, post 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); }
you can use strtol()
instead.
simply replace line:
sscanf(pos, "%2hhx", &val[count]);
with:
char buf[10]; sprintf(buf, "0x%c%c", pos[0], pos[1]); val[count] = strtol(buf, null, 0);
update: can avoid using sprintf()
using snippet instead:
char buf[5] = {"0", "x", pos[0], pos[1], 0}; val[count] = strtol(buf, null, 0);
Comments
Post a Comment