Question

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.

Was it helpful?

Solution 3

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.

OTHER TIPS

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...

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top