Convert a Byte Array to an Integer in Java

In Java there are several ways to convert a byte array into an integer. Let’s assume little endian order for all examples. If you need big endian order you can use can use Integer.reverseBytes.

1. ByteBuffer

byte[] byteArray = new byte[] {1, 2, 3, 4};
int intValue = ByteBuffer.allocate(4).put(byteArray).getInt(0);
System.out.println(intValue);
System.out.println(Integer.toBinaryString(intValue));

If you do not already use a ByteBuffer this is probably not the most efficient solution so let’s have a look another option.

2. BigInteger

byte[] byteArray = new byte[] {1, 2, 3, 4};
int intValue = new BigInteger(byteArray).intValue();
System.out.println(intValue);
System.out.println(Integer.toBinaryString(intValue));

But also in this method there is some overhead as new objects are created. So let’s see how to use low level bit operations in Java to achieve the same without new objects.

3. Bit Operation

byte[] b = new byte[] {1, 2, 3, 4};
int intValue = (b[3] & 0xFF) << 24
| (b[2] & 0xFF) << 16
| (b[1] & 0xFF) << 8
| (b[0] & 0xFF);
System.out.println(intValue);
System.out.println(Integer.toBinaryString(intValue));

So basically we shift each byte to the correct little endian positions and ensure that the unsigned byte is used. E.g. for byte b = -1 there would be higher bits set (implicit integer conversion) and with 0xFF we set them to zero, which ensures that the resulting (implicit) integer value represents the same numerical value as the byte. This also means that the expression (b[3] & 0xFF) << 24 is equivalent to b[3] << 24 but for the sake of clarity I avoided this optimization.

4. byteArrayViewVarHandle

Since Java 9 a lesser known but still efficient solution is to use MethodHandles and you basically “cast” the bytes into an integer like you would do in C/C++. You only need to define a static variable INT:

VarHandle INT = MethodHandles.byteArrayViewVarHandle(int[].class, ByteOrder.LITTLE_ENDIAN);

Then you can use INT like below:

byte[] b = new byte[] {1, 2, 3, 4};
int byteOffset = 0;
int intValue = (int) INT.get(b, byteOffset);
System.out.println(intValue);
System.out.println(Integer.toBinaryString(intValue));

The underlying implementation currently uses the lower level “Unsafe” method described in the next section.

5. Unsafe

To use Unsafe we need to obtain the instance:

static final Unsafe UNSAFE;
static {
    try {
        Field f = Unsafe.class.getDeclaredField("theUnsafe");
        f.setAccessible(true);
        UNSAFE = (Unsafe) f.get(null);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
static final int BYTE_ARRAY_OFFSET = UNSAFE.arrayBaseOffset(byte[].class);

Then you can use UNSAFE like below:

byte[] b = new byte[] {1, 2, 3, 4};
int byteOffset = 0;
int intValue = UNSAFE.getInt(b, byteOffset + BYTE_ARRAY_OFFSET);System.out.println(intValue);System.out.println(Integer.toBinaryString(intValue));