13

有人可以解释为什么以下声明:

short value = (short) 100000000;
System.out.println(value);

给我:

-7936

知道 Java 中 short 的最大值是 32767 对吗?

4

3 回答 3

23

以你一亿的价值,我得到-7936。1亿变成100万,只能得到16960。

原因是short值被限制在 -32768 到 +32767 之间,并且 Java 在转换为 a 时只保留最低有效 16 位short缩小原始转换,JLS 5.1.3)。实际上这个操作:100 万模 2^16(a 中的 16 位short)是 16960。

于 2013-09-17T22:23:08.480 回答
4

您这样做的方式只是重新解释了同一内存位置的少量位。它不会改变它们。

您可能希望使用maxandmin函数来检测值何时超出 ofshort并在发生这种情况时分配 short 的最大值或最小值。

int n = 1000000;
short value = n > Short.MAX_VALUE ? Short.MAX_VALUE : n < Short.MIN_VALUE ? Short.MIN_VALUE : (short)n;

更新:更紧凑:

import static java.lang.Math.max;
import static java.lang.Math.min;

// ...

value = (short)min(max(value, Short.MIN_VALUE), Short.MAX_VALUE);
System.out.println(value);
于 2013-09-17T22:23:11.840 回答
2

这是一篇很好的文章,解释了 Java 中的缩小和扩大原始转换。

short s = 696; // 0000 0010 1011 1000
byte x = (byte)s;
System.out.println("byte x = " + x);

产生:

byte x = -72

现在你应该明白为什么了——因为当我们缩小到字节时,JVM 会丢弃最重要的部分(00000010),结果(二进制形式)是 10111000。这与我们之前看到的数字相同。而且,如您所见,它是负数,与原始值不同。

于 2017-02-15T00:10:01.443 回答