Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format unsigned int into 8 digit hexadecimal number?

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?

like image 464
citronas Avatar asked Aug 20 '10 14:08

citronas


People also ask

How to print 8 digit Hex in C?

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

How to declare a hexadecimal number in C?

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.

Which formatting character is used to for hexadecimal?

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.

How do I get Hex in C++?

In C / C++ there is a format specifier %X. It prints the value of some variable into hexadecimal form.


2 Answers

Use "%08x" as your format string.

like image 68
PaulJWilliams Avatar answered Oct 13 '22 10:10

PaulJWilliams


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

like image 27
Frxstrem Avatar answered Oct 13 '22 10:10

Frxstrem