Java – 从Int到Short的显式转换
有人可以解释为什么以下声明:
short value = (short) 100000000; System.out.println(value);
给我:
16960
知道Java中short的最大值是32767是否正确?
你的价值1亿,我得到-7936。 如果我改变1亿到100万,我只能获得16960。
原因是short
值限制为-32768到+32767,并且Java在转换为short
( 缩小基元转换,JLS 5.1.3 )时仅保留最低有效16位。 实际上这个操作:100万mod 2 ^ 16(简称16位)是16960。
你这样做只是在同一个内存位置重新解释了较少的位数。 它不会改变它们。
您可能希望使用max
和min
函数来检测值何时超出short
并在发生时分配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);
这篇文章很好地解释了缩小和扩展Java中的原始转换。
short s = 696; // 0000 0010 1011 1000 byte x = (byte)s; System.out.println("byte x = " + x);
生产:
byte x = -72
现在你应该理解为什么 – 因为当我们缩小到字节时,JVM丢弃最重要的部分(00000010),结果(二进制forms)是10111000.这与我们之前看到的数字相同。 并且,正如您所看到的,与原始值不同,它是负面的。