When a long integer falls into a short, what happened?

I use java to copy one long integer y to a short integer x:

long y = 40002; short x = (short) y; System.out.println("x now equals " + x); 

Result: x is now -25534.

I tried to figure out how 40002 was added at -25534, but I failed. 40002 corresponds to 1001 1100 0100 0010, -25534 corresponds to 1110 0011 1011 1110. Can any friend tell me what happened in this process? Many thanks!

+5
source share
4 answers

What you did by discarding long to short is the narrowing of the primitive transform that JLS covers , section 5.1.3 :

Narrowing the conversion of a signed integer to an integral type T simply discards everything except n bits of the least significant bit, where n is the number of bits used to represent type T. In addition to the possible loss of information about the value, a numerical value can lead to the sign of the resulting values โ€‹โ€‹will differ from the sign of the input value.

The long 40002 is the following 64 bits:

 00000000 00000000 00000000 00000000 00000000 00000000 10011100 01000010 

The conversion only saves the lower 16 bits:

 10011100 01000010 

That the leading 1 interpreted in the 2 additions of the supplement as -2 ^ 15, and not + 2 ^ 15. This explains why there is a difference in 2 ^ 16, 65 536, in the long value and the short value.

+9
source

integer overflow occurred .

Two signed bytes are short, which means that Short.MAX_VALUE is 2 15 -1, which is 32 767. Larger values โ€‹โ€‹logically "wrap" in a negative range.

In this case, the excess amount is 40,002 - 2 15 = 7234
Short.MIN_VALUE is -2 15 = -32.768
-32.768 + 7234 = -25.534

which is the number you are thinking about.

+4
source

Thanks to everyone guys. For all your answers, I summarize the following: The long-term value of 40002 is the following 64 bits:

 00000000 00000000 00000000 00000000 00000000 00000000 10011100 01000010 

The conversion only saves the lower 16 bits:

 10011100 01000010 

When the JVM considers 10011100 01000010 as a short integer, it calculates it as follows:

 -2^15 + 00011100 01000010 = -32768 + 7234 = -25534 

It's him.

0
source

Basically, it will cycle through the values โ€‹โ€‹when you reach the maximum and add 1, it will be the lowest value, so 32768 will be -32768 when you reach 65536 (32768 * 2), it will be 0, and when you reach 98303 ( 32768 * 2 + 32767), it will be 32767, if you add it, you will get to 98304 (32768 * 3), and it will be -32768 again.

Thus, 40002 (which is higher than 32768, but lower than 32768 * 2) will obviously be a negative number when converting to short.

0
source

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


All Articles