converting bytes to int in Java

前端 未结 5 1263
隐瞒了意图╮
隐瞒了意图╮ 2021-01-05 05:24

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)
{

}
5条回答
  •  误落风尘
    2021-01-05 05:53

    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.

提交回复
热议问题