Java Utililty Methods Integer to Byte Array

List of utility methods to do Integer to Byte Array

Description

The list of methods to do Integer to Byte Array are organized into topic(s).

Method

byte[]intToByteArray(int value, int nrOfBytes)
Converts the given int value to an array of byte of given length.
byte[] result = new byte[nrOfBytes];
for (int i = 0; i < nrOfBytes && i < 4; i++) {
    result[nrOfBytes - 1 - i] = (byte) (value >>> (i * 8));
return result;
byte[]intToByteArray(int value, int numBytes)
int To Byte Array
if (numBytes < 1 || numBytes > 4)
    throw new RuntimeException("Bad");
byte[] actualByteArray = new byte[] { (byte) (value >>> 24), (byte) (value >>> 16), (byte) (value >>> 8),
        (byte) value };
byte[] out = new byte[numBytes];
System.arraycopy(actualByteArray, 4 - numBytes, out, 0, numBytes);
return out;
byte[]intToByteArray2(final int integer)
int To Byte Array
int byteNum = (40 - Integer.numberOfLeadingZeros(integer < 0 ? ~integer : integer)) / 8;
byte[] byteArray = new byte[4];
for (int n = 0; n < byteNum; n++)
    byteArray[3 - n] = (byte) (integer >>> (n * 8));
return new byte[] { byteArray[2], byteArray[3] };
byte[]intToByteArray4(int i)
Converts an integer number into a 4 bytes array
return new byte[] { (byte) ((i >> 24) & 0xff), (byte) ((i >> 16) & 0xff), (byte) ((i >> 8) & 0xff),
        (byte) (i & 0xff) };
byte[]intToByteArray4(int value)
Returns a byte array with length = 4
return new byte[] { (byte) (value >>> 24), (byte) (value >>> 16), (byte) (value >>> 8), (byte) value };
byte[]intToByteArrayBE(int data)
Convert an integer to a byte array (big endian).
return new byte[] { (byte) ((data >> 24) & 0xff), (byte) ((data >> 16) & 0xff), (byte) ((data >> 8) & 0xff),
        (byte) ((data >> 0) & 0xff), };
byte[]intToByteArrayLE(int v)
Convert an integer to byte array using Little Endian representation
return new byte[] { (byte) ((v & 0x000000FF)), (byte) ((v & 0x0000FF00) >> 8),
        (byte) ((v & 0x00FF0000) >> 16), (byte) ((v & 0xFF000000) >> 24) };
byte[]intToByteLittleEnding(int j)
int To Byte Little Ending
final byte[] bytes = new byte[4];
bytes[0] = (byte) (j & 0xff);
bytes[1] = (byte) ((j >>> 8) & 0xff);
bytes[2] = (byte) ((j >>> 16) & 0xff);
bytes[3] = (byte) ((j >>> 24) & 0xff);
return bytes;
byte[]intToByteMSB(int in)
int To Byte MSB
byte[] ou = new byte[4];
ou[0] = (byte) ((in >> 24) & 0xff);
ou[1] = (byte) ((in >> 16) & 0xff);
ou[2] = (byte) ((in >> 8) & 0xff);
ou[3] = (byte) (in & 0xff);
return ou;
intintToBytes(byte[] arr, int offset, int num)
int To Bytes
arr[offset + 0] = (byte) (num >> 24);
arr[offset + 1] = (byte) (num >> 16);
arr[offset + 2] = (byte) (num >> 8);
arr[offset + 3] = (byte) (num >> 0);
return INT_SIZE;