I need to convert my Integer value into byte array. In order not to create ByteBuffer again and again at every call for my intToBytes method I defined a static ByteBuffer.
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();
}
I get BufferOverflowException when I run intToBytes method.
W/System.err﹕ java.nio.BufferOverflowException W/System.err﹕ at java.nio.ByteArrayBuffer.putInt(ByteArrayBuffer.java:352) W/System.err﹕ at android.mobile.historian.Data.Convert.intToBytes(Convert.java:136)
In debug mode I see that capacity of the intBuffer is 4 as I expected for my Integer value. So what is wrong here?
You are overflowing the global buffer on second run of the function.
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();
}
Some context on ByteBuffer.putInt() : Writes the given int to the current position and increases the position by 4. The int is converted to bytes using the current byte order. Throws BufferOverflowException if position is greater than limit - 4. ReadOnlyBufferException if no changes may be made to the contents of this buffer.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments