tags:

views:

138

answers:

3

I need to convert 2 bytes (2's complement) into an int in Java code. how do I do it?

toInt(byte hb, byte lb)
{

}
+6  A: 
return ((int)hb << 8) | ((int)lb & 0xFF);

Correct operation in all cases is left as an exercise for the student.

Yann Ramin
Those casts are both redundant.
Mark Peters
Valid point, sometimes its clearer to be explicit.
Yann Ramin
A: 
public int toInt(byte hb, byte lb)
{
    return ((int)hb)<<8 + lb;
}
luke
is this answer the same as the one by theatrus?
no, it comes up with the wrong answer when lb is negative.
ILMTitan
+2  A: 

You can also use the ByteBuffer class:

public int toInt(byte hb, byte lb) {
    ByteBuffer bb = ByteBuffer.wrap(new byte[] {hb, lb});
    return bb.getShort(); // Implicitly widened to an int per JVM spec.
}

This class might be helpful if you're decoding a lot of data.

maerics
But if the two bytes are in 2's compliment, wouldn't that make the first byte of hb the sign bit? So your `new byte[]{a,b,c,d}` would be `a= hb b=0; c= hb d= lb;`? I could be off base here.
glowcoder
Good point, the first bit of `hb` should be pulled to the left-hand side of `a`, so my solution probably isn't what he's looking for. I just wanted to point out the ByteBuffer class...
maerics
Use `getShort` instead of `getInt`. When you cast the resulting `short` to an `int` it will be sign-extended giving the correct result.
finnw
@finnw: great idea, why didn't I think of that? =)
maerics