84

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.

Community
  • 1
  • 1
Petey B
  • 11,439
  • 25
  • 81
  • 101
  • Take a look at this: http://stackoverflow.com/questions/5399798/byte-array-and-int-conversion-in-java – TacB0sS Jun 03 '12 at 13:44

4 Answers4

145

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.

Waldheinz
  • 10,399
  • 3
  • 31
  • 61
  • 1
    This is better (gets the platform ByteOrder): `ByteBuffer.allocate(4).order(ByteOrder.nativeOrder()).putInt(yourInt).array();` – helmy Nov 13 '19 at 17:43
  • 2
    If it's better depends on what you want to do with it. It may be a little bit faster, but having the byte order depend on the platform is a no-no when you want to send those bytes over a network or even write to a file. – Waldheinz Nov 14 '19 at 20:29
50
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();
}
Perception
  • 79,279
  • 19
  • 185
  • 195
Hari Perev
  • 618
  • 5
  • 4
24

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.

Community
  • 1
  • 1
Miki
  • 7,052
  • 2
  • 29
  • 39
  • 1
    you should be aware of order. in that case order is big endian. from the most significant to the least. – Error Jul 07 '16 at 16:45
22
int integer = 60;
byte[] bytes = new byte[4];
for (int i = 0; i < 4; i++) {
    bytes[i] = (byte)(integer >>> (i * 8));
}
Franco Rondini
  • 10,841
  • 8
  • 51
  • 77
Stas Jaro
  • 4,747
  • 5
  • 31
  • 53