Printing the value of integer data type using %x in printf statement

1.3k views Asked by At

Got confused with the following peice of code.

#include <stdio.h>
void main()
{
int a=0100;
printf("%x",a);
}

The value I am getting is 40.

Can someone explain me whats going on here?

Note : When I removed the digit 0 before digit 1 then its coming 64 which is correct, when 100 is converted into hex.

Codepad link to above code

4

There are 4 answers

3
Bob Jarvis - Слава Україні On BEST ANSWER

In C, a constant prefixed with a 0 is an octal constant. 0100 in base 8 is 1000000 in base 2, which is 40 in hexadecimal, which is 64 in base 10. So your program is printing exactly what it should.

0
P.P On

Here

int a=0100;

you are assigning an octal value, which is 64 in base 10 and 40 is hex.

An integer literal starting with a 0 is octal in C.

0
Naomi On

a 0 prefix in c means octal, not decimal.

http://en.cppreference.com/w/cpp/language/integer_literal

  • decimal-literal is a non-zero decimal digit (1, 2, 3, 4, 5, 6, 7, 8, 9), followed by zero or more decimal digits (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
  • octal-literal is the digit zero (0) followed by zero or more octal digits (0, 1, 2, 3, 4, 5, 6, 7)
  • hex-literal is the character sequence 0x or the character sequence 0X followed by one or more hexadecimal digits (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, a, A, b, B, c, C, d, D, e, E, f, F)
  • binary-literal is the character sequence 0b or the character sequence 0B followed by one or more binary digits (0, 1)
0
Saurav Sahu On

0100 is a octal value as it has prefix 0.

0100 in octal (base 8)
 ^~~~(8^2)*1

is same as  

0x40  in hexadecimal (base 16)
  ^~~~(16^1)*4   // %x is for hexadecimal format

is same as 

64 in decimal (base 10)

printf("%o %x %d",a, a, a);  // prints 100 40 64