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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…