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
  • Liutauras Vilda
  • Tim Cooke
  • Paul Clapham
  • Jeanne Boyarsky
Sheriffs:
  • Ron McLeod
  • Frank Carver
  • Junilu Lacar
Saloon Keepers:
  • Stephan van Hulst
  • Tim Moores
  • Tim Holloway
  • Al Hobbs
  • Carey Brown
Bartenders:
  • Piet Souris
  • Frits Walraven
  • fred rosenberger

Casting int to byte (was: pls explain)

 
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Report post to moderator
byte i= (byte)129;
System.out.println(i);

output: -127 why?
can anyone explain?
[ April 25, 2007: Message edited by: Barry Gaunt ]
 
Ranch Hand
Posts: 447
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Report post to moderator
hi
vikram

byte range is -128 to 127

if you assign any value out of this range it will give compile time error
like this
byte b=130;

if you type cast to byte like this
byte b=(byte)130;
it will print -126

when it is out of range it again start from -128
so her the range exceeds by 3
-128,-127,-126
Thanks
anil kumar
 
Ranch Hand
Posts: 1710
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Report post to moderator


so her the range exceeds by 3



3 or 2?

Anyways,

A byte has 8 bit capacity, the most significant bit is for sign and all other
seven LSB (least significant bits) are for value.

If the limit exceeds, all the top bits of the the right hand side(int literal)
value is discarded.



Regards,
cmbhatt
 
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Report post to moderator
To avoid confusion please continue in this topic.
 
You ridiculous clown, did you think you could get away with it? This is my favorite tiny ad!
Garden Master Course kickstarter
https://coderanch.com/t/754577/Garden-Master-kickstarter
    Bookmark Topic Watch Topic
  • New Topic