Java - Convert int to Byte Array of 4 Bytes?

Petey B picture Petey B · Jun 16, 2011 · Viewed 132.6k times · Source

Possible Duplicate:
Convert integer into byte array (Java)

I need to store the length of a buffer, in a byte array 4 bytes large.

Pseudo code:

private byte[] convertLengthToByte(byte[] myBuffer)
{
    int length = myBuffer.length;

    byte[] byteLength = new byte[4];

    //here is where I need to convert the int length to a byte array
    byteLength = length.toByteArray;

    return byteLength;
}

What would be the best way of accomplishing this? Keeping in mind I must convert that byte array back to an integer later.

Answer

Waldheinz picture Waldheinz · Jun 16, 2011

You can convert yourInt to bytes by using a ByteBuffer like this:

return ByteBuffer.allocate(4).putInt(yourInt).array();

Beware that you might have to think about the byte order when doing so.