@Mysticial got it. A short is usually 16-bit and will illustrate the answer:
int main()
{
unsigned int x = 65529;
int y = (int) x;
printf("%d\n", y);
unsigned short z = 65529;
short zz = (short)z;
printf("%d\n", zz);
}
65529
-7
Press any key to continue . . .
So let's look at 65529 decimal. It can be represented as FFF9h
in hexadecimal. We can also represent that in binary as:
11111111 11111001
When we declare short zz = 65529;
, the compiler interprets 65529 as a signed value. In twos-complement notation, the top bit signifies whether a signed value is positive or negative. In this case, you can see the top bit is a 1
, so it is treated as a negative number. That's why it prints out -7
.
For an unsigned short
, we don't care about sign since it's unsigned
. So when we print it out using %d
, we use all 16 bits, so it's interpreted as 65529
.