• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Casting doubles to bytes

 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Author and all-around good cowpoke
Posts: 13078
6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 3451
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic