- A+

Category：Languages

I have to handle 8-byte unsigned integer type in Java somehow.

My 8-byte unsigned integer is stored in byte array wrapped by ByteBuffer. It comes from 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 **2^64-1** number and read it as **2^64-1**?

In Java's signed `long`

s, the most significant bit is worth -(2^{63}). If it were unsigned, then that bit would be worth positive 2^{63}. The difference is 2^{64}.

First, create a `BigInteger`

using the `long`

value. Then, if it's negative, apply the unsigned correction by adding 2^{64}, 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)); } `