Java - Explicit Conversion from Int to Short

瘦欲@ 提交于 2019-11-28 09:20:38

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

The reason is that short values 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.

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 max and min functions to detect when the value lies beyond of short and assign the max or min value of the short when that happens.

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

Here's good article explaining narrowing and widening primitive conversions in 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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!