Overflowing Short in java

前端 未结 4 1671
太阳男子
太阳男子 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:05

    What's happening is that your number is wrapping around. More specifically, you've got a number 30,000, which in binary is:

    0111 0101 0011 0000
    

    When you add it to itself, and carry the 1's, you get:

    1110 1010 0110 0000
    

    (Note: it's very easy to multiply a number by 2 in binary -- just shift all the bits one to the left.)

    A short is a signed number using two's complement, meaning that that leftmost 1 is really a minus sign; that number represents -5536.

    If you multiplied that number by 2 again, you'd need more than 2 bytes to represent it. Since you don't have more than 2 bytes in a short, the extra bits would just get dropped when the int result of the expression is narrowed to a short. Do that enough, and you'll have a 0 as the leftmost digit; the number is positive again. And then eventually you'll have a 1 again as the leftmost; the number is negative again. Eventually you'll have shifted all 0s into the number; multiplying any integer by 2 enough times will always result in 0 (specifically, if it's an N-bit number, multiplying it by 2 N times will always result in 0).

    If you weren't narrowing to a short, you'd still eventually run out of digits in the int (when you need 33 or more bits) -- this would result in the extra digits being dropped, which is integer overflow. The same thing would happen if either argument were a long, though it would take 65+ bits.

提交回复
热议问题