views:

109

answers:

3

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
+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
This worked for me, thank you for the example code.
Szere Dyeri
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
That's true. The example lacks any and all error-checking, edited to reflect that.
Michael Foukarakis
+1  A: 
char *hexstring = "deadbeef10203040b00b1e50", *pos = hexstring;
unsigned char val[12];
while( *pos )
{
  if( !((pos-hexstring)&1) )
    sscanf(pos,"%02x",&val[(pos-hexstring)>>1]);
  ++pos;
}

sizeof(val)/sizeof(val[0]) is redundant!