Java - Convert int to Byte Array of 4 Bytes? [duplicate] Java - Convert int to Byte Array of 4 Bytes? [duplicate] java java

Java - Convert int to Byte Array of 4 Bytes? [duplicate]


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.


public static  byte[] my_int_to_bb_le(int myInteger){    return ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN).putInt(myInteger).array();}public static int my_bb_to_int_le(byte [] byteBarray){    return ByteBuffer.wrap(byteBarray).order(ByteOrder.LITTLE_ENDIAN).getInt();}public static  byte[] my_int_to_bb_be(int myInteger){    return ByteBuffer.allocate(4).order(ByteOrder.BIG_ENDIAN).putInt(myInteger).array();}public static int my_bb_to_int_be(byte [] byteBarray){    return ByteBuffer.wrap(byteBarray).order(ByteOrder.BIG_ENDIAN).getInt();}


This should work:

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

Code taken from here.

Edit An even simpler solution is given in this thread.