Alex Alex - 1 year ago 46
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 Source

You need to know the endianness of your bytes.

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


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


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