Alex Alex - 5 months ago 10
Java Question

How can I convert a 4-byte array to an integer?

I want to perform a conversion without resorting to some implementation-dependent trick. Any tips?

Answer

You need to know the endianness of your bytes.

Assuming (like @WhiteFang34) that bytes is a byte[] of length 4, then...

Big-endian:

int x = java.nio.ByteBuffer.wrap(bytes).getInt();

Little-endian:

int x = java.nio.ByteBuffer.wrap(bytes).order(java.nio.ByteOrder.LITTLE_ENDIAN).getInt();