This week's book giveaway is in the Java in General forum.
We're giving away four copies of Event Streams in Action and have Alexander Dean & Valentin Crettaz on-line!
See this thread for details.
Win a copy of Event Streams in Action this week in the Java in General forum!
  • 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Devaka Cooray
  • Liutauras Vilda
  • Jeanne Boyarsky
  • Bear Bibeault
Sheriffs:
  • Paul Clapham
  • Knute Snortum
  • Rob Spoor
Saloon Keepers:
  • Tim Moores
  • Ron McLeod
  • Piet Souris
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Tim Holloway
  • Frits Walraven
  • Ganesh Patekar

Casting doubles to bytes

 
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
 
Author and all-around good cowpoke
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.
 
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.
 
What's brown and sticky? ... a stick. Or a tiny ad.
Java Code Review and Psychology
https://coderanch.com/t/714798/java/Java-Code-Review-Psychology
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!