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) { }
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) { }
return ((int)hb << 8) | ((int)lb & 0xFF);
Correct operation in all cases is left as an exercise for the student.
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.