views:

112

answers:

3

I have a fragment of bytes in a byte[]. The total size of the array is 4 and I want to convert this into a positive long number. For example if the byte array is having four bytes 101, 110, 10, 10000001 then i want to get the long number represented by binary sequence

00000000 00000000 00000000 00000000 00000101 00000110 00000010 10000001

which equals 84279937

What is the efficient way to do that in Java?

+4  A: 

Assuming little-endian,

(b[0] & 0xFF) | (b[1] & 0xFF) << 8 | (b[2] & 0xFF) << 16 | (b[3] & 0xFF) << 24

Example, http://www.ideone.com/p68zS

The & 0xFF is there to convert the signed bytes into unsigned...

KennyTM
I assume you meant bytes[3] | bytes[2] << 8 | bytes[1] << 16 | bytes[0] << 24 , as I want the first byte as the most significant.if i do this I am getting 111111111111111111111111111111111111111110000001This is the problem i want to solve. The last byte is treated as negative and when it is left shifted 24 bits, the first 40 bit are set to 1
sarav
KennyTM
KennyTM
sarav
+2  A: 

Don't know about efficiency, but since one of BigInteger's constructors gets a byte array, this may be a very simple way:

import java.math.BigInteger;

...

long value = new BigInteger(myByteArray).longValue();

Of course, you must take care that the bytes are given in two's complement and be aware that they are given in most-significant-byte first - so in your case you probably want to pad the beginning of your array with another 4 empty bytes.

Oak
+2  A: 
ByteBuffer buf = ByteBuffer.allocate(8); 
buf.put(4, b[0]).put(5, b[1]).put(6, b[2]).put(7, b[3]);
long longVal = buf.getLong();
GregS
This too works perfectly. Thanks.
sarav