convert int to short in C

前端 未结 5 1467
南旧
南旧 2020-12-19 03:19

I have:

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

and I get b = -1 whereas I expect int32 to be converted to

5条回答
  •  别那么骄傲
    2020-12-19 04:15

    Your int A is larger than the size of short. When you convert A to short, you get a 1 in the left most bit, which is going to indicate that it is a negative number. Since you're getting -1, I suppose you're getting 1s in all 16 bits, which is going to give you -2^15 + 2^14 + 2^13... + 2^0, which will give you -1. In short (no pun intended), you can't convert the integer to a short if it is too large.

提交回复
热议问题