开发者

bit manipulation in java

开发者 https://www.devze.com 2023-01-01 06:40 出处:网络
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 a开发者_开发问答rray is having four bytes 101,

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 a开发者_开发问答rray 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?


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


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.


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();
0

精彩评论

暂无评论...
验证码 换一张
取 消