4

我期待这个:

ByteBuffer.wrap(new byte[] { 0, 0, 0, -34 }).getInt() == 222

然而,以下是真实的:

ByteBuffer.wrap(new byte[] { 0, 0, 0, -34 }).getInt() == -570425344

我如何解决 Java 对有符号/无符号类型的许多限制,还是我需要完全自己动手?

4

2 回答 2

5

代码:

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。”—<a href="http://download.oracle.com/javase/6/docs/api/java/nio/ByteBuffer.html #order%28%29" rel="nofollow">ByteBuffer#order()

于 2011-06-16T02:46:29.173 回答
3

您观察到的结果对于 little-endian 机器是正确的。我怀疑如果你运行以下命令,你会得到LITTLE_ENDIAN答案。

ByteBuffer bb = ByteBuffer.wrap(new byte[] { 0, 0, 0, -34 });
System.out.println(bb.order());

如果要强制为缓冲区进行大端排序,请执行以下操作:

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
于 2011-06-16T03:00:50.937 回答