我正在尝试用ByteBuffer将4个字节的数组转换为int。以下是我尝试过的:
public static void main (String[] args) throws java.lang.Exception
{
int i = ByteBuffer.allocate(4)
.put(new byte[]{(byte) 0, (byte) 0, (byte) 0, (byte) 1})
.getInt(); //BufferUnderflowException
System.out.println(i);
}http://ideone.com/oULWJj
但是这个方法抛出了BufferUnderflowException。为什么?这有什么问题吗?
发布于 2017-05-14 18:31:07
为了阅读从ByteBuffer,你必须首先翻转它!
来自Javadoc of Buffer#flip
在一系列通道读取或放置操作之后,调用此方法为通道写入或相对get操作序列做准备。
示例:
ByteBuffer b = ByteBuffer.allocate(4);
b.put(new byte[]{(byte) 0, (byte) 0, (byte) 0, (byte) 1});
b.flip();
System.out.println(b.getInt());
>> 1发布于 2017-05-14 21:21:29
或者,创建ByteBuffer,使其最初包含字节,而不是put对它们进行处理:
System.out.println (ByteBuffer.wrap(new byte[]{0,0,0,1}).getInt());https://stackoverflow.com/questions/43967457
复制相似问题