【发布时间】:2014-09-24 16:49:33
【问题描述】:
我正在从设备读取 byte[] 并尝试在 ByteBuffer 类的帮助下将其解释为 Java 中的整数数组,但我遇到了索引越界错误。看这里:
byteBuffer.put(bytes); // put the array of bytes into the byteBuffer
System.out.println("the value I want is " + byteBuffer.getInt(16*4)); // gives me the number I want, but I'd rather deal with an integer array like this:
System.out.println("the value I want is " + byteBuffer.asIntBuffer().get(16)); // index out of bounds? Why??
【问题讨论】:
-
你能发布一个简短但完整的程序来演示这个问题吗?
-
我发现如果我在调用 byteBuffer.asIntBuffer() 之前执行 byteBuffer.position(0),它会起作用。必须这样做似乎很奇怪,但它确实有效。
-
可能是因为ByteBuffer的位置改变了。在
asIntBuffer的javadoc 中:新缓冲区的内容将从该缓冲区的当前位置开始。此缓冲区内容的更改将在新缓冲区中可见,反之亦然;两个缓冲区的位置、限制和标记值将是独立的。
标签: java bytebuffer