Convert int to byte array of 4 bytes?

Possible duplicate:
Convert integer to byte array (Java)

I need to save the length of the buffer, in a byte array - 4 bytes.

Pseudocode:

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 to do this? Remembering that I have to convert this byte array back to an integer later.

+54
java byte buffer
Jun 16 '11 at 16:01
source share
4 answers

You can convert yourInt to bytes using ByteBuffer as follows:

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

Beware, you may have to think about

+101
Jun 16 '11 at 16:05
source share
 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(); } 
+33
Apr 30 '12 at 8:16
source share

This should work:

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

The code is taken here .

Edit An even simpler solution is provided in this thread .

+18
Jun 16 2018-11-16T00:
source share
 int integer = 60; byte[] bytes = new byte[4]; for (int i = 0; i < 4; i++) { bytes[i] = (byte)(integer >>> (i * 8)); } 
+18
Jun 16 2018-11-16T00:
source share



All Articles