Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to correctly convert a Hex String to Byte Array in C?

I need to convert a string, containing hex values as characters, into a byte array. Although this has been answered already here as the first answer, I get the following error:

warning: ISO C90 does not support the ‘hh’ gnu_scanf length modifier [-Wformat]

Since I do not like warnings, and the omission of hh just creates another warning

warning: format ‘%x’ expects argument of type ‘unsigned int *’, but argument 3 has type ‘unsigned char *’ [-Wformat]

my question is: How to do this right? For completion, I post the 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);
}
like image 334
Alex Avatar asked Aug 16 '13 07:08

Alex


People also ask

Which method is used to convert a string to an array of bytes?

Using String. getBytes() The String class provides three overloaded getBytes methods to encode a String into a byte array: getBytes() – encodes using platform's default charset.

What is hex string in C?

Keep in mind that a string in C is an array of char values. And a char is an unsigned 8-bit quantity. (Just as an int is a signed 16-bit quantity.) The maximum value that can be placed in an unsigned 8-bit field is 255 decimal which is 0xFF hex or 0377 octal or 11111111 binary.


1 Answers

You can use strtol() instead.

Simply replace this 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: You can avoid using sprintf() using this snippet instead:

char buf[5] = {"0", "x", pos[0], pos[1], 0};
val[count] = strtol(buf, NULL, 0);
like image 92
mvp Avatar answered Sep 17 '22 01:09

mvp