Demir
Demir

Reputation: 1837

Convert int to byte array BufferOverflowException

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?

enter image description here

Upvotes: 1

Views: 1081

Answers (3)

Dexter
Dexter

Reputation: 1750

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.

Upvotes: 2

Duncan Jones
Duncan Jones

Reputation: 69339

Your code overflows the second time you call the method. This is because you've allocated enough space for one integer, but you've not reset the buffer. So when you call a second time, the buffer is already full and you get an exception.

Try this:

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

Side note: I doubt you need to cache this object.

Upvotes: 0

James Westman
James Westman

Reputation: 2690

You are running the function multiple times. Each time you run your function, it puts a new integer into the buffer after the first one. However, there is not enough room. You need to declare the byte buffer inside your function.

Upvotes: 0

Related Questions