For example
printf("%x",16);
This printf prints 10 instead of 16 why it is not take the value as hexadecimal pls someone explain this
For example
printf("%x",16);
This printf prints 10 instead of 16 why it is not take the value as hexadecimal pls someone explain this
When you pass a number to a function, you are not passing decimal or hexadecimal. Conceptually, you are passing a value, an abstract mathematical number.
That number is represented in some type, and C uses binary to represent values in integer types (along with some supplement of binary for signed numbers, usually two’s complement).
Whether you write printf("%x\n", 16u)
or printf("%x\n", 0x10u);
, the compiler converts that numeral in source code, 16u
or 0x10u
, to an unsigned int
value, represented in binary. It is that resulting value that is passed to printf
, not a decimal “16” or a hexadecimal “10”.
(I use 16u
and 0x10u
rather than 16
or 0x10
because printf
expects an unsigned int
, not an int
.)
The %x
directive tells printf
to expect an unsigned int
value and to convert it to a hexadecimal numeral. So the original input form is irrelevant; %x
means to produce hexadecimal regardless of the original form.
16
is a decimal integer constant. Thus the hexadecimal representation of the constant is10
. If you want to specify a hexadecimal integer constant then write0x16u
. Pay attention to that the conversion specifierx
expects an argument of the typeunsigned int
. So the suffixu
is used in the hexadecimal integer constant.So the call of
printf
can look likeand the output will be
16
.Or
and the output will be
0x16
.