views:

49

answers:

2

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?

+2  A: 

Use "%08x" as your format string.

Visage
+3  A: 

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

Frxstrem