我期望这样:
ByteBuffer.wrap(new byte[] { 0, 0, 0, -34 }).getInt() == 222
但是以下是正确的:
ByteBuffer.wrap(new byte[] { 0, 0, 0, -34 }).getInt() == -570425344
我如何解决 Java 对有符号/无符号类型的许多限制中的另一个问题,或者我是否需要完全自己动手?
最佳答案
代码:
public static void main(String[] args) {
ByteBuffer bb = ByteBuffer.wrap(new byte[] { 0, 0, 0, -34 });
System.out.println(bb.order());
System.out.println(bb.getInt() == 222);
bb.rewind();
bb.order(ByteOrder.LITTLE_ENDIAN);
System.out.println(bb.order());
System.out.println(bb.getInt() == -570425344);
}
控制台:
BIG_ENDIAN
true
LITTLE_ENDIAN
true
附录:作为引用,“新创建的字节缓冲区的顺序始终是 BIG_ENDIAN
。”— ByteBuffer#order()
关于将字节数组转换为整数的有符号和无符号类型的 Java ByteBuffer 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6366560/