[c] Format specifier %02x

I have a simple program :

#include <stdio.h>
int main()
{
        long i = 16843009;
        printf ("%02x \n" ,i);
}

I am using %02x format specifier to get 2 char output, However, the output I am getting is:

1010101 

while I am expecting it to be :01010101 .

This question is related to c printf format-specifiers

The answer is


%02x means print at least 2 digits, prepend it with 0's if there's less. In your case it's 7 digits, so you get no extra 0 in front.

Also, %x is for int, but you have a long. Try %08lx instead.


You are actually getting the correct value out.

The way your x86 (compatible) processor stores data like this, is in Little Endian order, meaning that, the MSB is last in your output.

So, given your output:

10101010

the last two hex values 10 are the Most Significant Byte (2 hex digits = 1 byte = 8 bits (for (possibly unnecessary) clarification).

So, by reversing the memory storage order of the bytes, your value is actually: 01010101.

Hope that clears it up!


%x is a format specifier that format and output the hex value. If you are providing int or long value, it will convert it to hex value.

%02x means if your provided value is less than two digits then 0 will be prepended.

You provided value 16843009 and it has been converted to 1010101 which a hex value.


Your string is wider than your format width of 2. So there's no padding to be done.