我正在阅读Unsigned arithmetic in Java,它很好地解释了如何使用以下方法进行无符号的longs

public static boolean isLessThanUnsigned(long n1, long n2) {
  return (n1 < n2) ^ ((n1 < 0) != (n2 < 0));
}

但是,我对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));
  }

最佳答案

也许有些图表有帮助。我将使用8位数字来使常量简短,它以明显的方式推广为int和longs。

绝对观点:

Unsigned number line:
                [ 0 .. 0x7F ][ 0x80 .. 0xFF]
Signed number line:
[ 0x80 .. 0xFF ][ 0 .. 0x7F]

相对视图:
Unsigned number line:
[ 0 .. 0x7F ][ 0x80 .. 0xFF]
Signed number line:
[ 0x80 .. 0xFF ][ 0 .. 0x7F]

因此,有符号和无符号数字在很大程度上具有相同的相对顺序,不同的是按顺序交换了设置了符号位和未设置符号位的两个范围。当然,反转该位会交换顺序。
x ^ Long.MIN_VALUE反转long的符号位。

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

07-24 09:28