我正在从设备读取 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??
Run Code Online (Sandbox Code Playgroud)
该类ByteBuffer在内部存储缓冲区的几个属性。最重要的是缓冲区中(虚拟“光标”)的位置。该位置可以用 读取byteBuffer.position(),也可以用 写入byteBuffer.position(123);。
现在的 JavaDocByteBuffer.asIntBuffer指出:
新缓冲区的内容将从该缓冲区的当前位置开始。
这意味着,例如,当您的 a 的ByteBuffer容量为 16 个元素,而position()this 的ByteBuffer容量为 4 时,那么结果IntBuffer将仅代表剩余的 12 个元素。
调用后byteBuffer.put(bytes),字节缓冲区的位置被提前(取决于字节数组的长度)。相应地,您所创建的容量IntBuffer也会较小。
要解决此问题,您可以在拨打电话后拨打byteBuffer.rewind()或。(哪一种更合适取决于预期的使用模式)byteBuffer.position(0)byteBuffer.put(bytes)