Java - Explicit conversion from Int to Short

Can someone explain why this is the following statement:

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

Gives me:

 -7936 

Knowing that the maximum short circuit value in Java is 32767, right?

+7
source share
3 answers

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 saves the lower 16 bits when passing to short (a narrowing of the primitive conversion, JLS 5.1.3 ). This operation is effective: 1 million modes 2 ^ 16 (16 bits in short ) - 16960.

+19
source

The way you did this simply reinterprets fewer bits in one memory location. He does not change them.

You probably want to use the max and min functions to detect when the value is outside of short , and assign the maximum or minimum value to the short when it happens.

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

Update: more compact:

 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); 
+2
source

Here is a good article explaining the narrowing and extension of primitive transformations in Java.

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

It produces:

 byte x = -72 

Now you have to understand why - because when we limit the byte, the JVM discards the most significant part (00000010) and the result (in binary form) is 10111000. This is the same number that we were looking before. And, as you can see, this is negative, in contrast to the original meaning.

0
source

Source: https://habr.com/ru/post/954027/


All Articles