2014-12-02 167 views
1

我需要将我的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值所期待的那样。那么这里有什么问题?

enter image description here

+1

闻起来像我过早的优化。你是否证明这个对象的重新创建是你的应用程序的瓶颈?如果没有,不要担心它... – 2014-12-02 12:44:15

回答

2

您正在溢出函数第二次运行时的全局缓冲区。

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 如果没有对此缓冲区的内容进行更改。

+0

我花了一段时间才注意到你的答案在这里。你应该在上面的代码中强调一下'clear()'的加入。代码下面的段落不适合这个问题。 – 2014-12-02 12:50:03

+0

恩,雅我有种回应在急速:/ – Dexter 2014-12-02 12:52:05

+0

谢谢@Dexter的答案。当我测试这个时,我也注意到我可以设置缓冲区的开始索引。如果我说intBuffer.putInt(0,Value);它的行为也像clear()一样。 – Demir 2014-12-02 16:05:48

0

您正在运行的功能多次。每次运行函数时,都会在第一个整数后加入一个新的整数。但是,没有足够的空间。你需要在函数中声明字节缓冲区。

0

第二次调用该方法时,代码溢出。这是因为你已经为一个整数分配了足够的空间,但是你没有重置缓冲区。所以当你第二次调用时,缓冲区已经满了,你会得到一个异常。

试试这个:

public static byte[] intToBytes(int Value) 
{ 
    intBuffer.clear(); 
    intBuffer.order(ByteOrder.LITTLE_ENDIAN); 
    intBuffer.putInt(Value); 
    return intBuffer.array(); 
} 

附注:我怀疑你需要缓存此对象。