5

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);
}
2
  • 1
    Consider strtol, this might help
    – bash.d
    Aug 16, 2013 at 7:18
  • Nothing that an extra variable can't solve. Aug 16, 2013 at 7:26

4 Answers 4

4

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);
3
  • 1
    Updated answer to avoid sprintf
    – mvp
    Aug 16, 2013 at 7:52
  • 4
    You can pass 16 as third argument of strtol instead of prefix "0x".
    – Vovanium
    Aug 16, 2013 at 11:35
  • I was solving this very similar using base 16 for strtol as @Vovanium mentioned and now I was able to get rid of sprintf as @mvp mentioned. Snippet looks like this: char t[5] = {fd, sd, 0}; d[c] = strtol(t, NULL, 16);
    – zevarito
    Jun 18, 2020 at 14:41
3

You can either switch your compiler to C99 mode (the hh length modifier was standardised in C99), or you can use an unsigned int temporary variable:

unsigned int byteval;
if (sscanf(pos, "%2x", &byteval) != 1)
{
    /* format error */
}
val[count] = byteval;
2

Why not do it without using sscanf, strol, etc. Below is HexToBin and as a free-bee, BinToHex. (Note originally there were returned enum error codes through an error logging system not a simple -1 return.)

unsigned char HexChar (char c)
{
    if ('0' <= c && c <= '9') return (unsigned char)(c - '0');
    if ('A' <= c && c <= 'F') return (unsigned char)(c - 'A' + 10);
    if ('a' <= c && c <= 'f') return (unsigned char)(c - 'a' + 10);
    return 0xFF;
}

int HexToBin (const char* s, unsigned char * buff, int length)
{
    int result;
    if (!s || !buff || length <= 0) return -1;

    for (result = 0; *s; ++result)
    {
        unsigned char msn = HexChar(*s++);
        if (msn == 0xFF) return -1;
        unsigned char lsn = HexChar(*s++);
        if (lsn == 0xFF) return -1;
        unsigned char bin = (msn << 4) + lsn;

        if (length-- <= 0) return -1;
        *buff++ = bin;
    }
    return result;
}

void BinToHex (const unsigned char * buff, int length, char * output, int outLength)
{
    char binHex[] = "0123456789ABCDEF";

    if (!output || outLength < 4) return;
    *output = '\0';

    if (!buff || length <= 0 || outLength <= 2 * length)
    {
        memcpy(output, "ERR", 4);
        return;
    }

    for (; length > 0; --length, outLength -= 2)
    {
        unsigned char byte = *buff++;

        *output++ = binHex[(byte >> 4) & 0x0F];
        *output++ = binHex[byte & 0x0F];
    }
    if (outLength-- <= 0) return;
    *output++ = '\0';
}
1

Using mvp's suggested change, I created this function which includes error checking (invalid characters and uneven length).

This function will convert a hexadecimal string - NOT prepended with "0x" - with an even number of characters to the number of bytes specified. It will return -1 if it encounters an invalid character, or if the hex string has an odd length, and 0 on success.

//convert hexstring to len bytes of data
//returns 0 on success, -1 on error
//data is a buffer of at least len bytes
//hexstring is upper or lower case hexadecimal, NOT prepended with "0x"
int hex2data(unsigned char *data, const unsigned char *hexstring, unsigned int len)
{
    unsigned const char *pos = hexstring;
    char *endptr;
    size_t count = 0;

    if ((hexstring[0] == '\0') || (strlen(hexstring) % 2)) {
        //hexstring contains no data
        //or hexstring has an odd length
        return -1;
    }

    for(count = 0; count < len; count++) {
        char buf[5] = {'0', 'x', pos[0], pos[1], 0};
        data[count] = strtol(buf, &endptr, 0);
        pos += 2 * sizeof(char);

        if (endptr[0] != '\0') {
            //non-hexadecimal character encountered
            return -1;
        }
    }

    return 0;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.