Zero Padding in C with printf#

In C, printf() can add leading zeros to make a number occupy a fixed minimum width.

The syntax is:

1
%0<width><specifier>

For example:

1
printf("%06d", 123);

Output:

1
000123

Here:

  • 0 → pad with zeros
  • 6 → minimum field width is 6 characters
  • d → print a signed decimal integer

Zero padding vs space padding#

1
printf("%06d", 123);

Output:

1
000123

while:

1
printf("%6d", 123);

Output:

1
   123

So:

1
2
%06d → zero padding
%6d  → space padding

Example: hexadecimal#

1
printf("0x%08lx\n", value);

For:

1
value = 0x1234;

the output is:

1
0x00001234

%08lx means:

  • 0 → zero padding
  • 8 → minimum width of 8 characters
  • llong
  • x → hexadecimal

Zero padding is useful when displaying IDs, hexadecimal values, timestamps, counters, or other fixed-width numbers where aligned output is desirable.