Reputation: 1
I am learning in C and I got a question regarding this conversion.
short int x = -0x52ea;
printf ( "%x", x );
output:
ffffad16
I would like to know how this conversion works because it's supposed to be on a test and we won't be able to use any compilers. Thank you
Upvotes: 0
Views: 83
Reputation: 154235
I would like to know how this conversion works
It is undefined behavior (UB)
short int x = -0x52ea;
0x52ea
is a hexadecimal constant. It has the value of 52EA16, or 21,22610. It has type int
as it fits in an int
, even if int
was 16 bit. OP's int
is evidently 32-bit.
-
negates the value to -21,226.
The value is assigned to a short int
which can encode -21,226, so no special issues with assigning this int
to a short int
.
printf("%x", x );
short int x
is passed to a ...
function, so goes through the default argument
promotions and becomes an int
. So an int
with the value -21,226 is passed.
"%x"
used with printf()
, expects an unsigned
argument. Since the type passed is not an unsigned
(and not an int
with a non-negative value - See exception C11dr §6.5.2.2 6), the result is undefined behavior (UB). Apparently the UB on your machine was to print the hex pattern of a 32-bit 2's complement of -21,226 or FFFFAD16
.
If the exam result is anything but UB, just smile and nod and realize the curriculum needs updating.
Upvotes: 4
Reputation: 27894
The point here is that when a number is negative, it's structured in a completely different way.
1 in 16-bit hexadecimal is 0001
, -1 is ffff
. The most relevant bit (8000
) indicates that it's a negative number (admitting it's a signed integer), and that's why it can only go as positive as 32767 (7fff
), and as negative as -32768 (8000
).
Basically to transform from positive to negative, you invert all bits and sum 1. 0001
inverted is fffe
, +1 = ffff
.
This is a convention called Two's complement and it's used because it's quite trivial to do arithmetic using bitwise operations when you use it.
Upvotes: 0