Is there a standard C function that can convert from hex string to bye array? I do not want to write my own function if there is an already existing standard way.
+2
A:
No. But it's relatively trivial to achieve using sscanf
in a loop.
Oli Charlesworth
2010-08-04 18:48:41
+2
A:
As far as I know, there's no standard function to do so, but it's simple to achieve in the following manner:
#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);
}
Hope this helps.
Edit
As Al pointed out, in case of an odd number of hex digits in the string, you have to make sure you prefix it with a starting 0. For example, the string "f00f5"
will be evaluated as {0xf0, 0x0f, 0x05}
erroneously by the above example, instead of the proper {0x0f, 0x00, 0xf5}
.
Michael Foukarakis
2010-08-04 19:40:18
This worked for me, thank you for the example code.
Szere Dyeri
2010-08-04 21:14:47
This is a good approach, but be aware that it will give an incorrect result if there is an odd number of digits in the hex string (the implicit zero will prefix the last digit, not the first, so "5ab5c" will be printed as 0x5ab50c rather than 0x05ab5c).
Al
2010-08-05 07:02:58
That's true. The example lacks any and all error-checking, edited to reflect that.
Michael Foukarakis
2010-08-05 08:00:57