Kamil :
I have to handle an 8-byte unsigned integer type in Java somehow.
My 8-byte unsigned integer is stored in a byte array wrapped by ByteBuffer. It comes from a data logger database and contains very big numbers.
This is how I deal with 4-byte integers to read them them as unsigned:
((long) (bytebuffer.getInt() & 0xFFFFFFFFL));
Unfortunately this:
((BigInteger) (bytebuffer.getLong() & 0xFFFFFFFFFFFFFFFFL));
doesn't work.
How can I store the number 2^64-1 and read it as 2^64-1?
rgettman :
In Java's signed long
s, the most significant bit is worth -(263). If it were unsigned, then that bit would be worth positive 263. The difference is 264.
First, create a BigInteger
using the long
value. Then, if it's negative, apply the unsigned correction by adding 264, or 1 << 64
, to the BigInteger
.
BigInteger result = BigInteger.valueOf(bytebuffer.getLong());
if (result.compareTo(BigInteger.ZERO) < 0) {
result = result.add(BigInteger.ONE.shiftLeft(64));
}