• Post Reply Bookmark Topic Watch Topic
  • New Topic

primitive casting  RSS feed

 
sonia jaswal
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
how do we cast from long to byte?
 
Balasubramanian Chandrasekaran
Ranch Hand
Posts: 215
Firefox Browser Linux VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi sonia,

You cannot do cast from long to byte.(Because,long is made up of 8 bytes of data).If you try to do then your data gets last.

Consider this code



You will get both the values same.But,once you increase the value of long_no to more than 127 your byte_no will get different values because it cannot hold the value in its memory.

I hope this would clarify your doubt.
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
[BC]: You cannot do cast from long to byte.(Because,long is made up of 8 bytes of data).If you try to do then your data gets last.

You certainly can cast a long to a byte, and your code above shows how. It also shows that for a value of 127, this creates no problem whatsoever. What the code doesn't show is that if the value is greater than 127, or less than -128, the value will be changed by the cast. Specifically, all higher-order bits will be set to zero. In some cases this is acceptable because you know that the value is in the range [-128, 127], and in other cases it's acceptable because you only care about the 8 lowest bits anyway.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!