Why (unsigned short) 0x8000 0001 is 1 not 65535?

-1

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?

c
casting
asked on Stack Overflow Jul 5, 2019 by Thuy Nguyen

2 Answers

4
  • 0x80000001 = 2147483649
  • The maximum value of unsigned short is 65535. One more than that is 65536.
  • "the value is converted by repeatedly... subtracting one more than the maximum value".
  • Repeadedly subtracting until value in range (smaller than 65536) is the same as modulus.
  • 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.

answered on Stack Overflow Jul 5, 2019 by Lundin
2

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.

answered on Stack Overflow Jul 5, 2019 by chux - Reinstate Monica • edited Jul 5, 2019 by chux - Reinstate Monica

User contributions licensed under CC BY-SA 3.0