Guava的UnsignedLong:为什么它是XOR Long.MIN_VALUE

Set*_*ron 6 java guava long-integer

我正在阅读Java中的无符号算术,它很好地解释了如何使用以下方法执行无符号长整数

public static boolean isLessThanUnsigned(long n1, long n2) {
  return (n1 < n2) ^ ((n1 < 0) != (n2 < 0));
}
Run Code Online (Sandbox Code Playgroud)

但是我对Guava的实现感到困惑.我希望有人可以对此有所了解.

  /**
   * A (self-inverse) bijection which converts the ordering on unsigned longs to the ordering on
   * longs, that is, {@code a <= b} as unsigned longs if and only if {@code flip(a) <= flip(b)} as
   * signed longs.
   */
  private static long flip(long a) {
    return a ^ Long.MIN_VALUE;
  }

  /**
   * Compares the two specified {@code long} values, treating them as unsigned values between
   * {@code 0} and {@code 2^64 - 1} inclusive.
   *
   * @param a the first unsigned {@code long} to compare
   * @param b the second unsigned {@code long} to compare
   * @return a negative value if {@code a} is less than {@code b}; a positive value if {@code a} is
   *     greater than {@code b}; or zero if they are equal
   */
  public static int compare(long a, long b) {
    return Longs.compare(flip(a), flip(b));
  }
Run Code Online (Sandbox Code Playgroud)

har*_*old 1

也许一些图表有帮助。我将使用 8 位数字来保持常量简短,它以明显的方式推广到整数和长整型。

绝对视图:

Unsigned number line:
                [ 0 .. 0x7F ][ 0x80 .. 0xFF]
Signed number line:
[ 0x80 .. 0xFF ][ 0 .. 0x7F]
Run Code Online (Sandbox Code Playgroud)

相对视图:

Unsigned number line:
[ 0 .. 0x7F ][ 0x80 .. 0xFF]
Signed number line:
[ 0x80 .. 0xFF ][ 0 .. 0x7F]
Run Code Online (Sandbox Code Playgroud)

因此,有符号数和无符号数基本上具有相同的相对顺序,只不过设置了符号位和未设置符号位的两个范围按顺序交换。当然,反转该位会交换顺序。

x ^ Long.MIN_VALUE反转 a 的符号位long

此技巧适用于仅依赖于相对顺序的任何操作,例如比较和直接相关的操作(例如最小值和最大值)。它不适用于依赖于数字绝对大小的运算,例如除法。