Originally posted by Lam Thai:
But do you know the logic behind it?
The logic is contained in the following phrases from the JLS section 5.1.3 quoted above:
About conversion from a floating point number: "A narrowing conversion of a floating-point number [... if the value is too large] the result of the first step is the largest representable value
of type int or long. In the second step: [...] If T is byte, char, or short, the result of the conversion
is the result of a narrowing conversion" (my emphasis)
About conversions between integral types (long, int, short): "A narrowing conversion of a signed integer to an integral type T simply discards all but the n lowest order bits [...]".
The difference between int casting and short casting is that a double can be directly cast to an int, but the casting to a short is a two step process which uses an integer narrowing conversion.
Line by line, this means:
long L = (long) d;
Since Double.MAX_VALUE cannot be represented in a long, the JLS dictates that the "largest representable value" is stored in L. Its bit
pattern is a 0 (positive sign) followed by sixty-three 1s.
int I1 = (int) d;
Again a conversion from a floating point number. The bit pattern for the largest positive number representable in an int is a 0 followed by thirty-one 1s.
int I2 = (int) L;
This is a conversion between integral types and simply discards the thirty-two highest order bits of L. What remains are thirty-two 1s, which is the bit pattern of the number -1.
short S1 = (short) d;
Again converting from a float. But now there is a two-step conversion process: first, the double is converted to an int (giving a 0 with thirty-one 1s); then, the int is narrowed to a short (only the sixteen lowest order 1s remain, which gives -1).
short S2 = (short) L;
Again this simply discards the highest order bits.
Hope this clears things up.
- Peter
[This message has been edited by Peter den Haan (edited May 01, 2001).]