java short 0,在Java中溢出Short

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 values that exceed the range, the result ends up being the supposed total minus either the positive range or the negative range times 2, as the following:

short a = 30000;

a = (short) (a+a);

the result is -5536.

So the math is 32768 + 32768 = 65536, 6000 - 65536 = -5536.

I know what it does, but I don't know why it does it this way.

Can anybody explain the logic or why Java is doing it this way?

解决方案

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值