3

I tried to convert int to byte[] and wrote for this following:

byte[] bytes = new byte[4];
ByteBuffer buff = ByteBuffer.allocate(4);
buff.putInt(1222);
buff.get(bytes);

but as result I had java.nio.BufferOverflowException without detail message.

As for me code is valid. What is wrong? How to convert int to byte[]?

2
  • At which line do you get the error? Commented Nov 4, 2016 at 13:07
  • buff.get(bytes) Commented Nov 4, 2016 at 13:09

4 Answers 4

6

You forgot to flip() your buffer after putting data in.

After you've put the int in the buffer, the position is at the end of the buffer. Trying to read data results in BufferUnderflowException (not overflow) since there are no bytes left to read in the buffer.

Sign up to request clarification or add additional context in comments.

Comments

6

A similar answer which doesn't require calling flip().

byte[] bytes = new byte[4];
ByteBuffer.wrap(bytes).putInt(0x12345678);
System.out.println(Arrays.toString(bytes));

prints http://ideone.com/Ab4Z4V

[18, 52, 86, 120]

This is 0x12, 0x34, 0x56 and 0x78

Comments

3

This is my approach to achieve it:

public static byte[] intToByteArray(int value) {
    if ((value >>> 24) > 0) {
        return new byte[]{
            (byte) (value >>> 24),
            (byte) (value >>> 16),
            (byte) (value >>> 8),
            (byte) value
        };
    } else if ((value >> 16) > 0) {
        return new byte[]{
            (byte) (value >>> 16),
            (byte) (value >>> 8),
            (byte) value
        };
    } else if ((value >> 8) > 0) {
        return new byte[]{
            (byte) (value >>> 8),
            (byte) value
        };
    } else {
        return new byte[]{
            (byte) value
        };
    }
}

Keep in mind, that this approach only use the number of bytes required to represent the number, that means if the number is small use less bytes.

Comments

2

Similar to your own solution but a bit more concise, the result is directly in the byte array.

    byte[] bytes = new byte[4];
    // BigEndian
    ByteBuffer.wrap(bytes).putInt(1222);
    // LittleEndian
    ByteBuffer.wrap(bytes).order(LITTLE_ENDIAN).putInt(1222);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.