Overflowing Short in java

前端 未结 4 1666
太阳男子
太阳男子 2020-11-30 15:23

I have one question about the short data type in Java. I know that the range for short is between -32768 to 32767.

So, if I tried to add two short value

4条回答
  •  攒了一身酷
    2020-11-30 16:14

    It has to do with the binary representation of data. In most systems, something called 2's complement is used. Positive numbers behave normally, as long as they have a leading 0.

    0010 = 2
    

    To flip the sign, replace all 0's with 1's, and add 1:

    -2 = 1110
    

    So what happens if we take the biggest positive number, say, 01111 (in binary), and add 1? We get 10000, which is a negative number (Int.min_val, specifically). That's what happens when an integer overflows.

    http://en.wikipedia.org/wiki/Two%27s_complement

提交回复
热议问题