#include <stdio.h>
#include <string.h>
main()
{
short int x=0x55AA;
printf("%x ",~x);
}
Above program gives output : ffffaa55. I was expecting o/p only aa55 as short int is 2 bytes. Can anyone please explain it?
#include <stdio.h>
#include <string.h>
main()
{
short int x=0x55AA;
printf("%x ",~x);
}
Above program gives output : ffffaa55. I was expecting o/p only aa55 as short int is 2 bytes. Can anyone please explain it?
You have:
short int x = 0x55AA;
~x;
The expression ~x
has the type int
.
C language never performs calculations in types narrower than [signed/unsigned] int
. Every time you use a value of narrower type (like short
or char
) in an expression, that value is implicitly promoted to [signed/unsigned] int
. One important detail here is that even if the original narrow type is unsigned
it will still be promoted to a signed type int
(assuming it fits into the range of int
). This is something that should be kept in mind in cases like that.
Note that it is not just the expression ~x
that has type int
, it is the x
itself that is promoted to int
even before the ~
has a chance to do anything. In other words, your ~x
is interpreted as ~(int) x
.
If you need a result of the original narrow type, you have to convert it back to the original type explicitly. In case of printf
, where explicit conversion won't solve anything (since variadic argument will be converted to int
anyway), you can use printf
format specifiers to interpret the corresponding argument a value of narrower type.
As a side note, %x
format specifier expects an argument of unsigned int
type. Passing negative int
value instead is not allowed.
Also, it is always a better idea to use unsigned types for any operations with bit-level semantics.
main()
{
short int x=0x55AA;
printf("%x ",~x);
}
Here,~x is treated as signed int.If you want o/p as aa55,then you should do typecast to unsigned short in.so,Try like this..
main()
{
short int x=0x55AA;
printf("%x ",(unsigned short int)~x);//typecasting
}
For the most part arithmetic and logic operators are defined for int and long, an expression involving smaller types involves an implicit conversion and the result will be the larger type.
Moreover "%x" is an unsigned int format specifier in any case.
There are various solutions, e.g.:
short x = 0x55AA ;
short nx = ~x ;
printf("%x ",~nx) ;
short x = 0x55AA ;
printf("%x ",~x & 0x0000FFFF ) ;