0

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
2
  • buf - as being of size 8 - will not contain a string terminating '\0'. Write char buf[9] if you want to use buf as a string as well, e.g. when writing printf("%s\n",buf) Commented Jul 14, 2018 at 20:36
  • 1
    What is actual HEX number. If I have a int variable how can I know if it is hex, octal, binary or decimal. Or maybe it is just the number. Commented Jul 14, 2018 at 20:51

1 Answer 1

1

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).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.