Converting 32-bit unsigned integer (big endian) to long and back
Asked Answered
I

3

8

I have a byte[4] which contains a 32-bit unsigned integer (in big endian order) and I need to convert it to long (as int can't hold an unsigned number).

Also, how do I do it vice-versa (i.e. from long that contains a 32-bit unsigned integer to byte[4])?

Inefficacious answered 24/3, 2012 at 20:1 Comment(1)
where does the byte array come from?Pleonasm
M
10

Sounds like a work for the ByteBuffer.

Somewhat like

public static void main(String[] args) {
    byte[] payload = toArray(-1991249);
    int number = fromArray(payload);
    System.out.println(number);
}

public static  int fromArray(byte[] payload){
    ByteBuffer buffer = ByteBuffer.wrap(payload);
    buffer.order(ByteOrder.BIG_ENDIAN);
    return buffer.getInt();
}

public static byte[] toArray(int value){
    ByteBuffer buffer = ByteBuffer.allocate(4);
    buffer.order(ByteOrder.BIG_ENDIAN);
    buffer.putInt(value);
    buffer.flip();
    return buffer.array();
}
Matchmaker answered 24/3, 2012 at 20:4 Comment(3)
Correct me if I'm wrong, but if I do int value = buffer.getInt(); then int might not be able to contain the whole number (if it is unsigned and not signed).Inefficacious
@Inefficacious An integer in Java is 32-bits (4 bytes), as long as your ByteBuffer is 4 bytes long, I do not see why there should be a problem. I have improved my answer and I tested it with positives and negatives and it works just fine so far. May I be missing something? If you intend to use unsigned integers then use longs and not integers, because integers in Java are signed.Matchmaker
You can use return buffer.getInt() & 0xFFFFFFFFL; as you will always get the unsigned value. ByteBuffer's are BIG_ENDIAN by default. You don't need to call flip() to use array()Cozen
T
10

You can use ByteBuffer, or you can do it the old-fashioned way:

long result = 0x00FF & byteData[0];
result <<= 8;
result += 0x00FF & byteData[1];
result <<= 8;
result += 0x00FF & byteData[2];
result <<= 8;
result += 0x00FF & byteData[3];
Thordis answered 24/3, 2012 at 20:9 Comment(0)
A
1

Guava has useful classes for dealing with unsigned numeric values.

http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/primitives/UnsignedInts.html#toLong(int)

Anode answered 24/3, 2012 at 20:10 Comment(2)
Good point, that is overwise just using the & 0xFFFFFFFFL method described by Peter Lawrey higher in one comment of this question.Hardie
Why toLong(Integer.MIN_VALUE) doesn't work? and return negative long ideone.com/cERLo1Algarroba

© 2022 - 2024 — McMap. All rights reserved.