Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I compare two longs as unsigned in Java?

I'm storing bit patterns of unsigned 64-bit numbers in a long variable and want to calculate the distance between two of them on the unsigned range. Because Java interprets long as a two's complement signed integer, I can't just do a - b, as the following example shows:

// on the unsigned range, these numbers would be adjacent
long a = 0x7fffffffffffffffL;
long b = 0x8000000000000000L;

// but as two's complement (or any representation that 
// stores the sign in the first bit), they aren't
assert b - a == 1;

What's the correct way to do this?

like image 887
Hanno Fietz Avatar asked Dec 02 '22 07:12

Hanno Fietz


1 Answers

Starting with Java 8, the comparison of long as unsigned integers can be done via Long.compareUnsigned(x, y).

Here is a simple backport for Java 7 and earlier:

public static int compareUnsigned(long x, long y) {
   return Long.compare(x + Long.MIN_VALUE, y + Long.MIN_VALUE);
}
like image 131
Nick Avatar answered Dec 29 '22 09:12

Nick