Convert integer into byte array (Java)
Have a look at the ByteBuffer class.
ByteBuffer b = ByteBuffer.allocate(4);//b.order(ByteOrder.BIG_ENDIAN); // optional, the initial order of a byte buffer is always BIG_ENDIAN.b.putInt(0xAABBCCDD);byte[] result = b.array();
Setting the byte order ensures that result[0] == 0xAA
, result[1] == 0xBB
, result[2] == 0xCC
and result[3] == 0xDD
.
Or alternatively, you could do it manually:
byte[] toBytes(int i){ byte[] result = new byte[4]; result[0] = (byte) (i >> 24); result[1] = (byte) (i >> 16); result[2] = (byte) (i >> 8); result[3] = (byte) (i /*>> 0*/); return result;}
The ByteBuffer
class was designed for such dirty hands tasks though. In fact the private java.nio.Bits
defines these helper methods that are used by ByteBuffer.putInt()
:
private static byte int3(int x) { return (byte)(x >> 24); }private static byte int2(int x) { return (byte)(x >> 16); }private static byte int1(int x) { return (byte)(x >> 8); }private static byte int0(int x) { return (byte)(x >> 0); }
Using BigInteger
:
private byte[] bigIntToByteArray( final int i ) { BigInteger bigInt = BigInteger.valueOf(i); return bigInt.toByteArray();}
Using DataOutputStream
:
private byte[] intToByteArray ( final int i ) throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(bos); dos.writeInt(i); dos.flush(); return bos.toByteArray();}
Using ByteBuffer
:
public byte[] intToBytes( final int i ) { ByteBuffer bb = ByteBuffer.allocate(4); bb.putInt(i); return bb.array();}