Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.1k views
in Technique[技术] by (71.8m points)

convert int to short in C

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...