Home > Net >  How to convert byte array to int/long
How to convert byte array to int/long

Time:04-03

I have these byte arrays: Byte Arrays

I have to order to little endian before to convert.

In first case, I do the conversion easyly:

byte[] serial = {-91, -101, 62, 55};
int serialNumber = java.nio.ByteBuffer.wrap(serial).order(ByteOrder.LITTLE_ENDIAN).getInt();
//serialNumber == 926849957 //Nice, works!!!!

In second case, the conversion doesn't works:

byte[] serial = {-45, 12, 115, -28};
int serialNumber = java.nio.ByteBuffer.wrap(serial).order(ByteOrder.LITTLE_ENDIAN).getInt();
//serialNumber == -462222125 //Wrong conversion. The right answer is 3832745171.

The number 3832745171 is larger than Integer.MAX_VALUE, but if I try to convert to long I got a problem too.

How can I do this? Thanks.

Try to convert byte arrays to int/long types.

CodePudding user response:

byte[] serial = {-45, 12, 115, -28};
int serialNumber = java.nio.ByteBuffer.wrap(serial).order(ByteOrder.LITTLE_ENDIAN).getInt();

This gives you the only representable equivalent of that in a Java int.

If you want it as an unsigned value, it will only be able to fit in a long, but you can write

Integer.toUnsignedLong(serialNumber)

(That said, you can just store it in an int. It's still the same value, it just does math differently and prints differently; you can convert it only when necessary.)

CodePudding user response:

3832745171 is the value if you could use unsigned integer, but it's not a valid value of a signed integer. It differs from -462222125 by Math.pow(2,32)

From the example in http://www.java2s.com/example/java/java.nio/get-unsigned-int-from-bytebuffer.html it seems possible to use a value in "long" to store the "Unsigned Integer" value.

Combining the logic in the link with your code, it would be like long serialNumber = ( java.nio.ByteBuffer.wrap(serial).order(ByteOrder.LITTLE_ENDIAN).getInt() & 0xFFFFFFFFL)

  • Related