Search code examples
cstrtoul

C - Convert Hex String to Int (with all 8 bits)


I'm trying to convert a hex string to an int (as hex still). I have it working, but there is a problem. If I enter the string "00000001" the result is 0x1. However, my function requires the full 8 bit values leading up to the 1. How can this be done?

I did see an example here on StackOverflow, but it's for C# and not C or C++.

Input:

Enter the memory address you want to dump from (EG: 0xABC00000)
address? >> 0x00000001

serial_buffer = 00000001
memory_address = "0x1"

Code:

unsigned int memory_address = 0xABC00000;
static char serial_buffer[30]; // plenty of room

memory_address = strtoul(serial_buffer, NULL, 16); // convert it

printf("serial_buffer = %s", serial_buffer);
printf("memory_address = \"0x%X\" bytes", memory_address);

// this is done in a loop (not part of this example)
serial_buffer[i++] = key_code; // add char into serial_buffer
putchar(key_code); // echo back the typed char

If I comment out memory_address = strtoul(serial_buffer, NULL, 16);, I get the correct value from the printf as memory_address = "0xABC00000".

If I then put memory_address = strtoul(serial_buffer, NULL, 16); back, I get from the printf a value of 0x1 (but I want it as 0x00000001).


Solution

  • I get from the printf a value of 0x1 (but I want it as 0x00000001).

    If you want to display a value using 8 digits, specify the minimum field width modifier and specify 0 to pad the field with zeros.

    printf("%08X", memory_address);
    

    You may read more at https://en.cppreference.com/w/c/io/fprintf .

    Note that 0x1 and 0x00000001 are exactly the same number, represented in different ways.

    Note, that: int has at least 16 bits and may be smaller than 32-bits, and strtoul returns a unsigned long. To print unsigned long use %lX format specifier.