我预料到了:
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()
您观察到的结果对于小端序机器来说是正确的。我怀疑如果您运行以下操作,您将得到LITTLE_ENDIAN
作为答案。
ByteBuffer bb = ByteBuffer.wrap(new byte[] { 0, 0, 0, -34 });
System.out.println(bb.order());
如果您想强制缓冲区的big-endian排序,请执行以下操作:
ByteBuffer bb = ByteBuffer.wrap(new byte[] { 0, 0, 0, -34 });
bb.order(ByteOrder.BIG_ENDIAN);
System.out.println(bb.order());
System.out.println(bb.getInt( ));
应打印出来:
BIG_ENDIAN
222