added _hex2bin()

This commit is contained in:
TLINDEN
2015-07-08 01:23:10 +02:00
parent 9ec01e2313
commit 4d68e52945

View File

@@ -83,3 +83,39 @@ char *_bin2hex(byte *bin, size_t len) {
out[len*2] = '\0';
return out;
}
/* via stackoverflow. yes, lazy */
size_t _hex2bin(const char *hex_str, unsigned char *byte_array, size_t byte_array_max) {
size_t hex_str_len = strlen(hex_str);
size_t i = 0, j = 0;
// The output array size is half the hex_str length (rounded up)
size_t byte_array_size = (hex_str_len+1)/2;
if (byte_array_size > byte_array_max)
{
// Too big for the output array
return -1;
}
if (hex_str_len % 2 == 1)
{
// hex_str is an odd length, so assume an implicit "0" prefix
if (sscanf(&(hex_str[0]), "%1hhx", &(byte_array[0])) != 1)
{
return -1;
}
i = j = 1;
}
for (; i < hex_str_len; i+=2, j++)
{
if (sscanf(&(hex_str[i]), "%2hhx", &(byte_array[j])) != 1)
{
return -1;
}
}
return byte_array_size;
}