48

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 .

Mini Bhati
  • 343
  • 5
  • 20
user2717225
  • 491
  • 1
  • 4
  • 5

4 Answers4

63

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

Chris Young
  • 15,627
  • 7
  • 36
  • 42
aragaer
  • 17,238
  • 6
  • 47
  • 49
  • 4
    I have learnt that 'x' in '%x' refers to hexadecimal format and not int. Is it so? – Rohit Kiran Jan 21 '15 at 13:41
  • 16
    `x` refers to "integer in hexadecimal format" as opposed to `d` which is "integer in decimal format". Both accept `int` as a value to be printed. `lx` and `ld` both accept `long`. – aragaer Jan 22 '15 at 00:28
  • 1
    For the sake of completenes also read https://stackoverflow.com/questions/15108932/c-the-x-format-specifier and http://www.cplusplus.com/reference/cstdio/printf/ – randmin Mar 22 '18 at 23:12
  • "Both accept int as a value to be printed" --> Hmmm, `"%x"` is for `unsigned`, not `int`. Common enough that `int` "works" though, even if not specified by C. – chux - Reinstate Monica Jun 23 '21 at 18:17
16

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

leiyc
  • 903
  • 11
  • 23
PulkitRajput
  • 609
  • 6
  • 8
2

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

PP.
  • 10,764
  • 7
  • 45
  • 59
-2

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!

Ahmed Akhtar
  • 1,444
  • 1
  • 16
  • 28
RJM
  • 73
  • 4
  • Uh no, printf is not printing the MSB to the right, that would be pretty confusing – eckes May 17 '17 at 08:59
  • 2
    Besides what eckes said, bit numbering inside of most processors isn't really a thing because you generally deal with a byte at a time. Bit ordering matters only for serialization. Endianness (big or little) is byte ordering, not bit ordering. – Daniel Papasian Aug 06 '17 at 16:09