将int转换为字节数组BufferOverflowException
我需要将我的Integer值转换为字节数组。为了不在每次调用我的intToBytes方法时重复创建ByteBuffer,我定义了一个静态ByteBuffer。将int转换为字节数组BufferOverflowException
private static ByteBuffer intBuffer = ByteBuffer.allocate(Integer.SIZE/Byte.SIZE);
public static byte[] intToBytes(int Value)
{
intBuffer.order(ByteOrder.LITTLE_ENDIAN);
intBuffer.putInt(Value);
return intBuffer.array();
}
我得到BufferOverflowException当我运行intToBytes方法。
W/System.err的:java.nio.BufferOverflowException W/System.err的:在java.nio.ByteArrayBuffer.putInt(ByteArrayBuffer.java:352) W/System.err的:在android.mobile.historian .Data.Convert.intToBytes(Convert.java:136)
在调试模式下,我看到intBuffer的容量是4,正如我对Integer值所期待的那样。那么这里有什么问题?
您正在溢出函数第二次运行时的全局缓冲区。
private static ByteBuffer intBuffer = ByteBuffer.allocate(Integer.SIZE/Byte.SIZE);
public static byte[] intToBytes(int Value)
{
intBuffer.clear(); //THIS IS IMPORTANT, YOU NEED TO RESET THE BUFFER
intBuffer.order(ByteOrder.LITTLE_ENDIAN);
intBuffer.putInt(Value);
return intBuffer.array();
}
上ByteBuffer.putInt一些上下文(): 写入给定的int到的当前位置和由4. 增加了位置的int被转换为使用当前的字节顺序字节。 抛出 BufferOverflowException 如果位置大于极限 - 4. ReadOnlyBufferException 如果没有对此缓冲区的内容进行更改。
您正在运行的功能多次。每次运行函数时,都会在第一个整数后加入一个新的整数。但是,没有足够的空间。你需要在函数中声明字节缓冲区。
第二次调用该方法时,代码溢出。这是因为你已经为一个整数分配了足够的空间,但是你没有重置缓冲区。所以当你第二次调用时,缓冲区已经满了,你会得到一个异常。
试试这个:
public static byte[] intToBytes(int Value)
{
intBuffer.clear();
intBuffer.order(ByteOrder.LITTLE_ENDIAN);
intBuffer.putInt(Value);
return intBuffer.array();
}
附注:我怀疑你需要缓存此对象。
闻起来像我过早的优化。你是否证明这个对象的重新创建是你的应用程序的瓶颈?如果没有,不要担心它... – 2014-12-02 12:44:15