Java - 从 Int 到 Short 的显式转换

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18860817/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 11:41:53  来源:igfitidea点击:

Java - Explicit Conversion from Int to Short

javavariablescastingintshort

提问by Octocat

Can someone please explain why this following statement:

有人可以解释为什么下面的语句:

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

Gives me:

给我:

-7936

Knowing that the maximum value of a short in Java is 32767 correct?

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

采纳答案by rgettman

With your value of 100 million, I get -7936. I can only get 16960 if I change 100 million to 1 million.

以你的价值1亿,我得到-7936。如果我把1亿换成100万,我只能得到16960。

The reason is that shortvalues are limited to -32768 to +32767, and Java only keeps the least significant 16 bits when casting to a short(a narrowing primitive conversion, JLS 5.1.3). Effectively this operation: 1 million mod 2^16 (16 bits in a short) is 16960.

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

回答by necromancer

The way you did it merely reinterprets a smaller number of bits at the same memory location. It does not change them.

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

You probably want to use the maxand minfunctions to detect when the value lies beyond of shortand assign the max or min value of the short when that happens.

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

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

Update:more compactly:

更新:更紧凑:

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

回答by tworec

Here'sgood article explaining narrowing and widening primitive conversions in Java.

这是解释 Java 中缩小和扩大原始转换好文章。

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

Produces:

byte x = -72

Now you should understand why - because when we narrow short down to the byte the JVM discards the most significant part (00000010) and the result (in binary form) is 10111000. This is the same number we were looking at before. And, as you can see, it is negative, unlike the original value.

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

产生:

byte x = -72

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