我正在从设备中读取一个字节[],并尝试在ByteBuffer类的帮助下将其解释为Java中的整数数组,但我得到的索引超出了界限错误。看这里:Java ByteBuffer类
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??
你可以发布一个简短但完整的程序来演示问题吗? – 2014-09-24 16:55:15
我发现它的作品,如果我在调用byteBuffer.asIntBuffer()之前做了一个byteBuffer.position(0)。似乎很奇怪必须这样做,但它的工作。 – Barodapride 2014-09-24 16:57:07
可能是因为ByteBuffer的位置发生了变化。在'asIntBuffer'的javadoc中:新缓冲区的内容将从这个缓冲区的当前位置开始。这个缓冲区内容的改变将在新缓冲区中可见,反之亦然;两个缓冲区的位置,限制和标记值将是独立的。 – user1071777 2014-09-24 16:58:10