I want to format an unsigned int to an 8 digit long string with leading zeroes.
This is what I have so far:
unsigned int number = 260291273;
char output[9];
sprintf(output, "%x", number);
printf("%s\n", output); // or write it into a file with fputs
Prints "f83bac9", but I want "0f83bac9". How can I achieve the formatting?
Printing the number in Hexadecimal format To print integer number in Hexadecimal format, "%x" or "%X" is used as format specifier in printf() statement. "%x" prints the value in Hexadecimal format with alphabets in lowercase (a-f). "%X" prints the value in Hexadecimal format with alphabets in uppercase (A-F).
In C programming language, hexadecimal value is represented as 0x or 0X and to input hexadecimal value using scanf which has format specifiers like %x or %X.
The AHEX format is used to read the hexadecimal representation of standard characters. Each set of two hexadecimal characters represents one standard character. The w specification refers to columns of the hexadecimal representation and must be an even number.
In C / C++ there is a format specifier %X. It prints the value of some variable into hexadecimal form.
Use "%08x" as your format string.
You can use zero-padding by specifying 0
and the number of digits you want, between %
and the format type.
For instance, for hexadecimal numbers with (at least) 8 digits, you'd use %08x
:
printf("%08x", number);
Output (if number
is 500):
000001f4
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With