Mirai Mann Mirai Mann - 1 month ago 22
Java Question

How to convert int to byte[]?

I tried to convert

int
to
byte[]
and wrote for this following:

byte[] bytes = new bytes[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[]
?

Answer

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.