Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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])?

like image 950
Aviram Avatar asked Mar 24 '12 20:03

Aviram


3 Answers

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();
}
like image 189
Edwin Dalorzo Avatar answered Nov 14 '22 19:11

Edwin Dalorzo


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];
like image 20
Hot Licks Avatar answered Nov 14 '22 18:11

Hot Licks


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)

like image 1
Sam Barnum Avatar answered Nov 14 '22 19:11

Sam Barnum