Markus
Markus

Reputation: 319

C Programming convert String representation of Hex to Hex

I am fairly new to C. I would like to convert a String representation of a HEX number to a actual Hex number ?

#include <stdio.h>
int main()
    {
        char buf[8] = "410C0000";
        printf("%s\n",buf);
        return 0;
    }

I would like to break up the string and convert it into 4 inividual Hex numbers. Which i can process further for calculations :

0x41 0x0C 0x00 0x00

Upvotes: 0

Views: 1738

Answers (1)

Stephan Lechner
Stephan Lechner

Reputation: 35164

You can use sscanf, which is a variant of scanf that reads from a string rather than from a stdin or a file. Format specifier %X specifies to treat the input as a hexadecimal number, %02X additionally says to read exactly two digits, and %02hhX additionally defines to store the result into a single byte (i.e. an unsigned char, instead of a probably 64 bit integral value).

The code could look as follows:

int main()
{
    char buf[8] = "410C0000";

    unsigned char h0=0, h1=0, h2=0, h3=0;
    sscanf(buf+6, "%02hhX", &h0);
    sscanf(buf+4, "%02hhX", &h1);
    sscanf(buf+2, "%02hhX", &h2);
    sscanf(buf+0, "%02hhX", &h3);
    printf("0x%02X 0x%02X 0x%02X 0x%02X\n",h3, h2, h1, h0);
    return 0;
}

Output:

0x41 0x0C 0x00 0x00

BTW: buf - as being of size 8 - will not contain a string terminating '\0', so you will not be able to use it in printf. Write char buf[9] if you want to use buf as a string as well, e.g. when writing printf("%s\n",buf).

Upvotes: 1

Related Questions