首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Java ByteBuffer类

Java ByteBuffer类
EN

Stack Overflow用户
提问于 2014-09-24 16:49:33
回答 1查看 846关注 0票数 3

我正在从一个设备中读取一个byte[],并试图在ByteBuffer类的帮助下将它解释为一个整数数组,但是我得到了一个超出界限的索引。看这里:

代码语言:javascript
复制
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??
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-09-24 16:58:39

ByteBuffer类内部存储缓冲区的几个属性。最重要的是(虚拟“游标”)在缓冲区中的位置。这个位置可以用byteBuffer.position()读取,也可以用byteBuffer.position(123);编写。

JavaDoc of ByteBuffer.asIntBuffer现在声明:

新缓冲区的内容将从该缓冲区的当前位置开始。

这意味着,例如,当您有一个容量为16个元素的ByteBuffer,并且该ByteBufferposition()为4时,则生成的IntBuffer将只表示其余的12个元素。

调用byteBuffer.put(bytes)后,字节缓冲区的位置将被提前(取决于字节数组的长度)。因此,您正在创建的IntBuffer具有较小的容量。

要解决这个问题,可以在调用byteBuffer.rewind()byteBuffer.position(0)之后调用byteBuffer.put(bytes)。(哪一种更合适,取决于预期的使用模式)

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26022359

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档