user2717225
user2717225

Reputation: 551

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 .

Upvotes: 54

Views: 194759

Answers (4)

PulkitRajput
PulkitRajput

Reputation: 669

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

Upvotes: 18

RJM
RJM

Reputation: 71

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!

Upvotes: -3

aragaer
aragaer

Reputation: 17858

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

Upvotes: 68

PP.
PP.

Reputation: 10865

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

Upvotes: 2

Related Questions