Search code examples
ctype-conversionhexunsigned-char

I can't understand how to convert hex string to unsigned char in C?


I have input

unsigned char hex[64] =  9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a0"

and I want output like this:

unsigned char tmpInHash[32] = { 0x9f, 0x86, 0xd0, 0x81, 0x88, 0x4c, 0x7d, 0x65, 0x9a, 0x2f, 0xea, 0xa0, 0xc5, 0x5a, 0xd0, 0x15, 0xa3, 0xbf, 0x4f, 0x1b, 0x2b, 0x0b, 0x82, 0x2c, 0xd1, 0x5d, 0x6c, 0x15, 0xb0, 0xf0, 0x0a, 0x08 }

I searched for the answer everywhere, but the answers , which I found, do not fit.

EDIT

I want that when I write:

for(i=0; i< strlen(tmpInHash); i++ {
    printf("%c ", tmpInHash);
}

I get this:

0x9f 0x86 0xd0 0x81 0x88 0x4c 0x7d 0x65 0x9a ...

Is it possible?


Solution

  • One way to convert this is the following way:

    • Iterate through every item of the string, where every 2 characters represent a number.
    • Break out each such character pair and store them in a temporary string: char tmp {str[i], str[i+1], '\0'};.
    • Call strtol(tmp, NULL, 16) on this string to get the integer number.