Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When a long integer is cast into a short one, what happened?

Tags:

java

casting

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

The result is: x now equals -25534.

I tried to figure out how 40002 was cast into -25534, but I failed. The 40002 corresponds to 1001 1100 0100 0010, the -25534 corresponds to 1110 0011 1011 1110. Can any friend tell me what happened in this process? Thanks a lot!

like image 909
microbit Avatar asked Jan 16 '15 21:01

microbit


1 Answers

What you have done by casting a long to a short is a narrowing primitive conversion, which is covered by the JLS, Section 5.1.3:

A narrowing conversion of a signed integer to an integral type T simply discards all but the n lowest order bits, where n is the number of bits used to represent type T. In addition to a possible loss of information about the magnitude of the numeric value, this may cause the sign of the resulting value to differ from the sign of the input value.

The long value 40002 is the following 64 bits:

00000000 00000000 00000000 00000000 00000000 00000000 10011100 01000010

The conversion only retains the least significant 16 bits:

10011100 01000010

That leading 1 is interpreted in 2's complement notation to be -2^15, not +2^15. That explains why there is a difference of 2^16, of 65,536, in the long value and the short value.

like image 122
rgettman Avatar answered Sep 20 '22 20:09

rgettman