Something puzzles me, and I did not find much information about the specifications of VM. This is a bit unclear, and it would be nice if someone could explain to me.
These are a few lines of code .....
double myTest = Double.MAX_VALUE; System.out.println("1. float: " + (float)myTest); System.out.println("2. int: " + (int)myTest); System.out.println("3. short: " + (short)myTest); System.out.println("4. byte: " + (byte)myTest);
..... produce this conclusion:
- float: infinity
- int: 2147483647
- short: -1
- byte: -1
byte
, short
and int
- 8, 16, 32 bits with two additions. float
and double
- 32 and 64 bits of IEEE 754 ( see here ).
From my understanding, the maximum value of a double
implies that all the mantissa bits (52 bits) are switched to 1. Therefore, it is (very) not surprising that casting to short or byte returns -1 i.e. all bits are switched to 1. It seems that the cast holds the tail of the double
so that it enters 8 byte
bits or 16 short
bits.
What surprises me is casting to int
and, to a lesser extent, casting to float
. How can I get "2. int: 2147483647", which is 0x7FFFFFFF, the maximum value while short and bytes 3. and 4. are -1?
Casting to float
also weird. If the 32 bits in the tail of myTest
were stored, then it should not generate NaN
?
source share