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