0

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.

2
  • Int64 if available? Commented Apr 2, 2022 at 16:30
  • I tried, but I was not successful. Commented Apr 2, 2022 at 20:02

2 Answers 2

0

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)

Sign up to request clarification or add additional context in comments.

Comments

0
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.)

1 Comment

I tried, but I was not successful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.