printf() formatting for hex

wsmccusker picture wsmccusker · Feb 6, 2013 · Viewed 609.8k times · Source

This is more of a curious query than an important question, but why when printing hex as an 8 digit number with leading zeros, does this %#08X Not display the same result as 0x%08X?

When I try to use the former, the 08 formatting flag is removed, and it doesn't work with just 8.

Again I was just curious.

Answer

Mike picture Mike · Feb 6, 2013

The # part gives you a 0x in the output string. The 0 and the x count against your "8" characters listed in the 08 part. You need to ask for 10 characters if you want it to be the same.

int i = 7;

printf("%#010x\n", i);  // gives 0x00000007
printf("0x%08x\n", i);  // gives 0x00000007
printf("%#08x\n", i);   // gives 0x000007

Also changing the case of x, affects the casing of the outputted characters.

printf("%04x", 4779); // gives 12ab
printf("%04X", 4779); // gives 12AB