How read java long as unsigned long and store value in BigInteger?

  • A+

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 longs, 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)); } 


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: