Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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

like image 946
alexgolec Avatar asked Sep 06 '25 03:09

alexgolec


1 Answers

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();
like image 145
rlibby Avatar answered Sep 07 '25 21:09

rlibby