在Java中溢出Short [英] Overflowing Short in java

查看:307
本文介绍了在Java中溢出Short的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Java中的 short 数据类型有一个疑问。我知道短期的范围在-32768到32767之间。

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

所以,如果我试图添加两个超出范围的短值,结果最终是假设总数减去正范围或负范围乘以2,如下所示:

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);

结果为 -5536

所以数学 32768 + 32768 = 65536 6000 - 65536 = -5536

我知道它的作用,但我不知道为什么会这样做。

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

任何人都可以解释逻辑或为什么Java这样做?

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

推荐答案

正在发生的事情是你的号码正在四处传播。更具体地说,你有一个30,000,二进制是:

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

当你将它添加到自身并携带1时,你得到:

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

1110 1010 0110 0000

(注意:它非常容易将数字乘以2乘以二进制 - 只需将所有位移到左边。)

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

短是使用两个补码,意味着最左边的1实际上是一个减号;该数字代表-5536。

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

如果再将该数字乘以2,则需要超过2个字节来表示它。由于 short 中的字节数不超过2个,所以当 int 时,额外的位将被删除表达式的结果缩小为 short 。做到这一点,你将得到一个0作为最左边的数字;这个数字又是正数。然后最终你将再次作为最左边的1;这个数字又是负数。最终你将所有0都转换为数字;将任何整数乘以2足够的时间总是会得到0(具体来说,如果它是一个N位数,则乘以2 N次将总是得到0)。

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).

如果你没有缩小到,你最终还是会用完 int 中的数字(当你需要33位或更多位时 - 这会导致额外的数字被删除,这是整数溢出。如果任一参数是 long ,同样的事情会发生,尽管它需要65+位。

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.

这篇关于在Java中溢出Short的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆