reign_man
reign_man

Reputation: 569

Bitwise or not producing expected results

I have the following java code:

public static void main(String []args){
    int a = 1;
    byte b = -14;
    int c = (a << 8) | b;

    System.out.println(c);
 }

Which produces:

-14

I would have expected 498. As I understand things, the OR operation will look like this after shifting: 1 0000 0000 | 1111 0010, and I would expect this to result in an int that looks like 0000 0001 1111 0010, for a value of 498. Clearly Java is somehow sign extending the bytes when it OR's them into int c. Can anyone show me the correct way to do this?

What I'm trying to do is make an int where the least significant byte is b and the 2nd least significant byte is a.

Upvotes: 0

Views: 87

Answers (3)

reign_man
reign_man

Reputation: 569

You can't do this easily/well with bitwise operators in java. The solution is to use a ByteBuffer.

ByteBuffer byteBuffer = ByteBuffer.allocate(4);
byteBuffer.put((byte)0);
byteBuffer.put((byte)0);
byteBuffer.put((byte)1);
byteBuffer.put((byte)-14);
byteBuffer.rewind();
int bodyLength = byteBuffer.getInt();
System.out.println(bodyLength);

The above code will print 498.

Upvotes: 0

chauhraj
chauhraj

Reputation: 499

Remember a is byte. So when you do a << 8, won't it shift 8 positions right, effectively making it 0. It promotes the result to int. I would suggest to define a as int.

Updated:

int c = ((a << 8) | ~(~0 << 8) & b); will result in expected answer of 498

Upvotes: 1

nhgrif
nhgrif

Reputation: 62072

If you shift everything in a byte 8 bits, you've shifted everything completely off. ORing with a completely zeroed out byte is the same as adding zero or multiplying by 1...

Upvotes: 2

Related Questions