2014-12-02 169 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(); 
} 

附註:我懷疑你需要緩存此對象。