Although Java has no unsigned long type, you can treat signed 64-bit two's-complement integers (i.e. long
values) as unsigned if you are careful about it.
Many primitive integer operations are sign agnostic for two's-complement representations. For example, you can use Java primitive addition, subtraction and multiplication on an unsigned number represented as a long
, and get the "right" answer.
For other operations such as division and comparison, the Long
class provides method like divideUnsigned
and compareUnsigned
that will give the correct results for unsigned numbers represented as long
values.
The Long
methods supporting unsigned operations were added in Java 8. Prior to that, you could use 3rd-party libraries to achieve the same effect. For example, the static methods in the Guava UnsignedLongs
class.
Is BigInteger
the signed long that Java supports?
BigInteger
would be another way to represent integer values greater that Long.MAX_VALUE
. But BigInteger
is a heavy-weight class. It is unnecessary if your numbers all fall within the range 0 to 264 - 1 (inclusive).