• Post Reply Bookmark Topic Watch Topic
  • New Topic

Casting doubles to bytes  RSS feed

 
Tim J Eyre
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
William Brogden
Author and all-around good cowpoke
Rancher
Posts: 13078
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If I was investigating this further I would see what the doubleToLongBits method returned for those double values.

I suspect that the low byte of that long is what you are seeing.
 
Michael Morris
Ranch Hand
Posts: 3451
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!