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).
CodePudding user response:
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("X", 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.
CodePudding user response:
why don't you just use sscanf (not to be confused with scanf)
it takes input string, format string and output:
int size;
char buffer[30];
/*...*/
sscanf(buffer, "0x%x", &size);
sscanf info here
formatting here
CodePudding user response:
Regarding this answer: https://stackoverflow.com/a/10156436/16046121
I think you should use strtoul with the base 0 because you are getting the input as
address? >> 0x00000001
not as 00000001.
