Format specifier %02x

140,343

Solution 1

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

Solution 2

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

Solution 3

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

Share:
140,343
Admin
Author by

Admin

Updated on June 21, 2020

Comments

  • Admin
    Admin almost 4 years

    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 .

  • Rohit Kiran
    Rohit Kiran over 9 years
    I have learnt that 'x' in '%x' refers to hexadecimal format and not int. Is it so?
  • aragaer
    aragaer over 9 years
    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.
  • Prashant
    Prashant about 7 years
    Uh no, printf is not printing the MSB to the right, that would be pretty confusing
  • bloodphp
    bloodphp almost 7 years
    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.
  • randmin
    randmin about 6 years
  • chux - Reinstate Monica
    chux - Reinstate Monica almost 3 years
    "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.