简体   繁体   中英

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

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 (ie 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, eg when writing printf("%s\\n",buf) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM