Static utility methods pertaining to long primitives that interpret values as unsigned (that is, any negative value x is treated as the positive value 2^64 + x). The methods for which signedness is not an issue are in Longs, as well as signed versions of method
| 49 | |
| 50 | |
| 51 | @Beta |
| 52 | @GwtCompatible |
| 53 | public final class UnsignedLongs { |
| 54 | private UnsignedLongs() {} |
| 55 | |
| 56 | |
| 57 | public static final long MAX_VALUE = -1L; // Equivalent to 2^64 - 1 |
| 58 | |
| 59 | /** |
| 60 | * A (self-inverse) bijection which converts the ordering on unsigned longs to the ordering on |
| 61 | * longs, that is, {@code a <= b} as unsigned longs if and only if {@code flip(a) <= flip(b)} as |
| 62 | * signed longs. |
| 63 | */ |
| 64 | private static long flip(long a) { |
| 65 | return a ^ Long.MIN_VALUE; |
| 66 | } |
| 67 | |
| 68 | /** |
| 69 | * Compares the two specified {@code long} values, treating them as unsigned values between |
| 70 | * {@code 0} and {@code 2^64 - 1} inclusive. |
| 71 | * |
| 72 | * @param a the first unsigned {@code long} to compare |
| 73 | * @param b the second unsigned {@code long} to compare |
| 74 | * @return a negative value if {@code a} is less than {@code b}; a positive value if {@code a} is |
| 75 | * greater than {@code b}; or zero if they are equal |
| 76 | */ |
| 77 | |
| 78 | |
| 79 | public static int compare(long a, long b) { |
| 80 | return Longs.compare(flip(a), flip(b)); |
| 81 | } |
| 82 | |
| 83 | /** |
| 84 | * Returns the least value present in {@code array}, treating values as unsigned. |
| 85 | * |
| 86 | * @param array a <i>nonempty</i> array of unsigned {@code long} values |
| 87 | * @return the value present in {@code array} that is less than or equal to every other value in |
| 88 | * the array according to {@link #compare} |
| 89 | * @throws IllegalArgumentException if {@code array} is empty |
| 90 | */ |
| 91 | |
| 92 | |
| 93 | public static long min(long... array) { |
| 94 | checkArgument(array.length > 0); |
| 95 | long min = flip(array[0]); |
| 96 | for (int i = 1; i < array.length; i++) { |
| 97 | long next = flip(array[i]); |
| 98 | if (next < min) { |
| 99 | min = next; |
| 100 | } |
| 101 | } |
| 102 | return flip(min); |
| 103 | } |
| 104 | |
| 105 | /** |
| 106 | * Returns the greatest value present in {@code array}, treating values as unsigned. |
| 107 | * |
| 108 | * @param array a <i>nonempty</i> array of unsigned {@code long} values |