在Java中将字节转换为int

use*_*196 8 java byte

我需要在Java代码中将2个字节(2的补码)转换为int.我该怎么做?

toInt(byte hb, byte lb)
{

}

Yan*_*min 15

return ((int)hb << 8) | ((int)lb & 0xFF);
Run Code Online (Sandbox Code Playgroud)

所有情况下的正确操作都留给学生练习.

  • 那些演员都是多余的. (5认同)
  • 如果你不想失去精度,你需要用“&amp;0xFF”来做到这一点。像这样: return (hb &amp; 0xFF) &lt;&lt; 8 | (磅和0xFF); (2认同)

mae*_*ics 10

您还可以使用ByteBuffer类:

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.
}
Run Code Online (Sandbox Code Playgroud)

如果您要解码大量数据,此类可能会有所帮助.