Logo 
Search:

Java Forum

Ask Question   UnAnswered
Home » Forum » Java       RSS Feeds

Representing byte as int

  Asked By: Ronnie    Date: Jan 14    Category: Java    Views: 689
  

Could somebody please explain to me why it is that
when I execute:

byte b = 203;
int i = (int)b;

I get i as a negative number (which makes sense b'c
the byte represents a neg. number in 2's complement),
yet when I execute this:

int i = (int)b & 0xFF

I get a value for i as if b were an unsigned byte?

Share: 

 

1 Answer Found

 
Answer #1    Answered By: Jonathan Brown     Answered On: Jan 14

firstly this line wouldn't work:

byte  b = 203;

as number literals are of type int  so you'd need to do this:

byte b = (byte)203;

After this line, b contains 11001011. When this line executes:

> int i = (int)b;

It is extended to 32 bits to make it int. The most significant bit is
1 so the rest is filled with 1s like this:

11111111111111111111111111001011

which is -53

When you execute  this line:

> int i = (int)b & 0xFF

You're doing this:

11111111111111111111111111001011 & 11111111

which just gives you 11001011 or 203.

 
Didn't find what you were looking for? Find more on Representing byte as int Or get search suggestion and latest updates.




Tagged: