convert int to short in C

user1128265 picture user1128265 · Aug 16, 2013 · Viewed 54.2k times · Source

I have:

int a = 2147483647;
short b = (short)a;

and I get b = -1 whereas I expect int32 to be converted to int16(short). I expect to see some value and not -1.

Please someone help me with this.

Answer

Sergey Kalinichenko picture Sergey Kalinichenko · Aug 16, 2013

The value 2147483647, or 231-1 overflows a 16-bit integer. Its binary representation is zero in the MSB followed by 31 ones in the remaining bits.

It looks like in your implementation the last 16 bits are taken in the conversion to short. When this happens, all of them are set to 1, resulting in a 2's complement representation of -1:

32-bit int:   01111111111111111111111111111111
16-bit short: ----------------1111111111111111

However, neither the 2-compliment representation nor this behavior in general is part of the C++ standard, so this behavior is implementation-defined.