Please can someone tell me why casting a double greater than the max int value into a byte will simply chop off the leftmost bits yielding -1 or 0, yet if the double in less than the max size for an int then we get the double value modulused by the byte range. Is there an implicit conversion into an int somewhere here? for example: double d1 = 3000000000d; double d2 = 2000000010d; byte b; b = (byte)d1; System.out.println("b casted from d1 = " + b); b = (byte)d2; System.out.println("b casted from d2 = " + b); results in the following: b casted from d1 = -1 b casted from d2 = 10 Many Thanks Tim
Is there an implicit conversion into an int somewhere here? Bingo! That is exactly what happens. Take a look at the disassembled code of this portion of your example:
Here is the disassembly (using javap -c TestDoubleCast):
Take a look at offsets 4-6 on the main assembly, the double is loaded into the accumulator (4), the double is cast to an int (5), the int is cast to a byte (6). The cast to int results in the maximum value for an int of 2147483647 or 0x7FFFFFFF and casting that to a byte results in 0xFF or -1 in two's complement form.
Any intelligent fool can make things bigger, more complex, and more violent. It takes a touch of genius - and a lot of courage - to move in the opposite direction. - Ernst F. Schumacher
What's brown and sticky? ... a stick. Or a tiny ad.