C 11 6.3.1.3, for cast:
Otherwise, if the new type is unsigned, the value is converted by repeatedly adding or subtracting one more than the maximum value that can be represented in the new type until the value is in the range of the new type.
When I try
printf("%d", (unsigned short) 0x80000001);
I expect the result is 65535
but I got 1
.
Why 1
is returned in this case?
0x80000001
= 2147483649
unsigned short
is 65535
. One more than that is 65536
.2147483649 % 65536
= 1
.But this is the formal theory - in practice, this is the very same as simply taking the lowest 16 bits of 0x80000001
, which is the value 0x0001
.
USHRT_MAX
, in OP's case is 65535. (unsigned short) 0x80000001
converts to 1 per C 11 6.3.1.3 as cited.
The unsigned short 1
is certainly converted to int 1
per the integer promotion as part being an argument to a ... function. This matches "%d"
and "1"
is printed.
User contributions licensed under CC BY-SA 3.0