我正在从一个设备中读取一个byte[],并试图在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:58:39
ByteBuffer类内部存储缓冲区的几个属性。最重要的是(虚拟“游标”)在缓冲区中的位置。这个位置可以用byteBuffer.position()读取,也可以用byteBuffer.position(123);编写。
JavaDoc of ByteBuffer.asIntBuffer现在声明:
新缓冲区的内容将从该缓冲区的当前位置开始。
这意味着,例如,当您有一个容量为16个元素的ByteBuffer,并且该ByteBuffer的position()为4时,则生成的IntBuffer将只表示其余的12个元素。
调用byteBuffer.put(bytes)后,字节缓冲区的位置将被提前(取决于字节数组的长度)。因此,您正在创建的IntBuffer具有较小的容量。
要解决这个问题,可以在调用byteBuffer.rewind()或byteBuffer.position(0)之后调用byteBuffer.put(bytes)。(哪一种更合适,取决于预期的使用模式)
https://stackoverflow.com/questions/26022359
复制相似问题