Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Copyright (C) 2011 The Guava Authors
   *
   * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
   * in compliance with the License. You may obtain a copy of the License at
   *
   * http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software distributed under the
  * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
  * express or implied. See the License for the specific language governing permissions and
  * limitations under the License.
  */
 
 package com.google.common.primitives;
 
 import static com.google.common.base.Preconditions.checkArgument;
 import static com.google.common.base.Preconditions.checkNotNull;
 
 
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 methods for which signedness is an issue.

In addition, this class provides several static methods for converting a long to a String and a String to a long that treat the long as an unsigned number.

Users of these utilities must be extremely careful not to mix up signed and unsigned long values. When possible, it is recommended that the UnsignedLong wrapper class be used, at a small efficiency penalty, to enforce the distinction in the type system.

See the Guava User Guide article on unsigned primitive utilities.

Author(s):
Louis Wasserman
Brian Milch
Colin Evans
Since:
10.0
 
 public final class UnsignedLongs {
   private UnsignedLongs() {}
 
   public static final long MAX_VALUE = -1L; // Equivalent to 2^64 - 1
 
  
A (self-inverse) bijection which converts the ordering on unsigned longs to the ordering on longs, that is, a <= b as unsigned longs if and only if flip(a) <= flip(b) as signed longs.
 
   private static long flip(long a) {
     return a ^ .;
   }

  
Compares the two specified long values, treating them as unsigned values between 0 and 2^64 - 1 inclusive.

Parameters:
a the first unsigned long to compare
b the second unsigned long to compare
Returns:
a negative value if a is less than b; a positive value if a is greater than b; or zero if they are equal
 
   public static int compare(long along b) {
     return Longs.compare(flip(a), flip(b));
   }

  
Returns the least value present in array, treating values as unsigned.

Parameters:
array a nonempty array of unsigned long values
Returns:
the value present in array that is less than or equal to every other value in the array according to compare(long,long)
Throws:
java.lang.IllegalArgumentException if array is empty
 
   public static long min(long... array) {
     checkArgument(array.length > 0);
     long min = flip(array[0]);
     for (int i = 1; i < array.lengthi++) {
       long next = flip(array[i]);
       if (next < min) {
         min = next;
       }
     }
     return flip(min);
   }

  
Returns the greatest value present in array, treating values as unsigned.

Parameters:
array a nonempty array of unsigned long values
Returns:
the value present in array that is greater than or equal to every other value in the array according to compare(long,long)
Throws:
java.lang.IllegalArgumentException if array is empty
  public static long max(long... array) {
    checkArgument(array.length > 0);
    long max = flip(array[0]);
    for (int i = 1; i < array.lengthi++) {
      long next = flip(array[i]);
      if (next > max) {
        max = next;
      }
    }
    return flip(max);
  }

  
Returns a string containing the supplied unsigned long values separated by separator. For example, join("-", 1, 2, 3) returns the string "1-2-3".

Parameters:
separator the text that should appear between consecutive values in the resulting string (but not at the start or end)
array an array of unsigned long values, possibly empty
  public static String join(String separatorlong... array) {
    checkNotNull(separator);
    if (array.length == 0) {
      return "";
    }
    // For pre-sizing a builder, just get the right order of magnitude
    StringBuilder builder = new StringBuilder(array.length * 5);
    builder.append(toString(array[0]));
    for (int i = 1; i < array.lengthi++) {
      builder.append(separator).append(toString(array[i]));
    }
    return builder.toString();
  }

  
Returns a comparator that compares two arrays of unsigned long values lexicographically. That is, it compares, using compare(long,long)), the first pair of values that follow any common prefix, or when one array is a prefix of the other, treats the shorter array as the lesser. For example, [] < [1L] < [1L, 2L] < [2L] < [1L << 63].

The returned comparator is inconsistent with java.lang.Object.equals(java.lang.Object) (since arrays support only identity equality), but it is consistent with java.util.Arrays.equals(long[],long[]).

See also:
Lexicographical order article at Wikipedia
  public static Comparator<long[]> lexicographicalComparator() {
  }
  enum LexicographicalComparator implements Comparator<long[]> {
    INSTANCE;
    @Override
    public int compare(long[] leftlong[] right) {
      int minLength = Math.min(left.lengthright.length);
      for (int i = 0; i < minLengthi++) {
        if (left[i] != right[i]) {
          return UnsignedLongs.compare(left[i], right[i]);
        }
      }
      return left.length - right.length;
    }
  }

  
Returns dividend / divisor, where the dividend and divisor are treated as unsigned 64-bit quantities.

Parameters:
dividend the dividend (numerator)
divisor the divisor (denominator)
Throws:
java.lang.ArithmeticException if divisor is 0
  public static long divide(long dividendlong divisor) {
    if (divisor < 0) { // i.e., divisor >= 2^63:
      if (compare(dividenddivisor) < 0) {
        return 0; // dividend < divisor
      } else {
        return 1; // dividend >= divisor
      }
    }
    // Optimization - use signed division if dividend < 2^63
    if (dividend >= 0) {
      return dividend / divisor;
    }
    /*
     * Otherwise, approximate the quotient, check, and correct if necessary. Our approximation is
     * guaranteed to be either exact or one less than the correct value. This follows from fact
     * that floor(floor(x)/i) == floor(x/i) for any real x and integer i != 0. The proof is not
     * quite trivial.
     */
    long quotient = ((dividend >>> 1) / divisor) << 1;
    long rem = dividend - quotient * divisor;
    return quotient + (compare(remdivisor) >= 0 ? 1 : 0);
  }

  
Returns dividend % divisor, where the dividend and divisor are treated as unsigned 64-bit quantities.

Parameters:
dividend the dividend (numerator)
divisor the divisor (denominator)
Throws:
java.lang.ArithmeticException if divisor is 0
Since:
11.0
  public static long remainder(long dividendlong divisor) {
    if (divisor < 0) { // i.e., divisor >= 2^63:
      if (compare(dividenddivisor) < 0) {
        return dividend// dividend < divisor
      } else {
        return dividend - divisor// dividend >= divisor
      }
    }
    // Optimization - use signed modulus if dividend < 2^63
    if (dividend >= 0) {
      return dividend % divisor;
    }
    /*
     * Otherwise, approximate the quotient, check, and correct if necessary. Our approximation is
     * guaranteed to be either exact or one less than the correct value. This follows from fact
     * that floor(floor(x)/i) == floor(x/i) for any real x and integer i != 0. The proof is not
     * quite trivial.
     */
    long quotient = ((dividend >>> 1) / divisor) << 1;
    long rem = dividend - quotient * divisor;
    return rem - (compare(remdivisor) >= 0 ? divisor : 0);
  }

  
Returns the unsigned long value represented by the given decimal string.

Throws:
java.lang.NumberFormatException if the string does not contain a valid unsigned long value
java.lang.NullPointerException if s is null (in contrast to java.lang.Long.parseLong(java.lang.String))
  public static long parseUnsignedLong(String s) {
    return parseUnsignedLong(s, 10);
  }

  
Returns the unsigned long value represented by the given string. Accepts a decimal, hexadecimal, or octal number given by specifying the following prefix:
  • 0xHexDigits
  • 0XHexDigits
  • #HexDigits
  • 0OctalDigits

Throws:
java.lang.NumberFormatException if the string does not contain a valid unsigned long value
Since:
13.0
  public static long decode(String stringValue) {
    ParseRequest request = ParseRequest.fromString(stringValue);
    try {
      return parseUnsignedLong(request.rawValuerequest.radix);
    } catch (NumberFormatException e) {
      NumberFormatException decodeException =
          new NumberFormatException("Error parsing value: " + stringValue);
      decodeException.initCause(e);
      throw decodeException;
    }
  }

  
Returns the unsigned long value represented by a string with the given radix.

Parameters:
s the string containing the unsigned long representation to be parsed.
radix the radix to use while parsing s
Throws:
java.lang.NumberFormatException if the string does not contain a valid unsigned long with the given radix, or if radix is not between java.lang.Character.MIN_RADIX and java.lang.Character.MAX_RADIX.
java.lang.NullPointerException if s is null (in contrast to java.lang.Long.parseLong(java.lang.String))
  public static long parseUnsignedLong(String sint radix) {
    checkNotNull(s);
    if (s.length() == 0) {
      throw new NumberFormatException("empty string");
    }
    if (radix < . || radix > .) {
      throw new NumberFormatException("illegal radix: " + radix);
    }
    int max_safe_pos = [radix] - 1;
    long value = 0;
    for (int pos = 0; pos < s.length(); pos++) {
      int digit = Character.digit(s.charAt(pos), radix);
      if (digit == -1) {
        throw new NumberFormatException(s);
      }
      if (pos > max_safe_pos && overflowInParse(valuedigitradix)) {
        throw new NumberFormatException("Too large for unsigned long: " + s);
      }
      value = (value * radix) + digit;
    }
    return value;
  }

  
Returns true if (current * radix) + digit is a number too large to be represented by an unsigned long. This is useful for detecting overflow while parsing a string representation of a number. Does not verify whether supplied radix is valid, passing an invalid radix will give undefined results or an ArrayIndexOutOfBoundsException.
  private static boolean overflowInParse(long currentint digitint radix) {
    if (current >= 0) {
      if (current < [radix]) {
        return false;
      }
      if (current > [radix]) {
        return true;
      }
      // current == maxValueDivs[radix]
      return (digit > [radix]);
    }
    // current < 0: high bit is set
    return true;
  }

  
Returns a string representation of x, where x is treated as unsigned.
  public static String toString(long x) {
    return toString(x, 10);
  }

  
Returns a string representation of x for the given radix, where x is treated as unsigned.

Parameters:
x the value to convert to a string.
radix the radix to use while working with x
Throws:
java.lang.IllegalArgumentException if radix is not between java.lang.Character.MIN_RADIX and java.lang.Character.MAX_RADIX.
  public static String toString(long xint radix) {
    checkArgument(radix >= . && radix <= .,
        "radix (%s) must be between Character.MIN_RADIX and Character.MAX_RADIX"radix);
    if (x == 0) {
      // Simply return "0"
      return "0";
    } else {
      char[] buf = new char[64];
      int i = buf.length;
      if (x < 0) {
        // Separate off the last digit using unsigned division. That will leave
        // a number that is nonnegative as a signed integer.
        long quotient = divide(xradix);
        long rem = x - quotient * radix;
        buf[--i] = Character.forDigit((intremradix);
        x = quotient;
      }
      // Simple modulo/division approach
      while (x > 0) {
        buf[--i] = Character.forDigit((int) (x % radix), radix);
        x /= radix;
      }
      // Generate string
      return new String(bufibuf.length - i);
    }
  }
  // calculated as 0xffffffffffffffff / radix
  private static final long[] maxValueDivs = new long[. + 1];
  private static final int[] maxValueMods = new int[. + 1];
  private static final int[] maxSafeDigits = new int[. + 1];
  static {
    BigInteger overflow = new BigInteger("10000000000000000", 16);
    for (int i = .i <= .i++) {
      [i] = divide(i);
      [i] = (intremainder(i);
      [i] = overflow.toString(i).length() - 1;
    }
  }
New to GrepCode? Check out our FAQ X