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 int primitives that interpret values as unsigned (that is, any negative value x is treated as the positive value 2^32 + x). The methods for which signedness is not an issue are in com.google.common.primitives.Ints, as well as signed versions of methods for which signedness is an issue.

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

Users of these utilities must be extremely careful not to mix up signed and unsigned int values. When possible, it is recommended that the com.google.common.primitives.UnsignedInteger 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
Since:
11.0
 
 public final class UnsignedInts {
   static final long INT_MASK = 0xffffffffL;
 
   private UnsignedInts() {}
 
   static int flip(int value) {
     return value ^ .;
   }

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

Parameters:
a the first unsigned int to compare
b the second unsigned int 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(int aint b) {
     return Ints.compare(flip(a), flip(b));
   }

  
Returns the value of the given int as a long, when treated as unsigned.
 
   public static long toLong(int value) {
     return value & ;
   }

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

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

  
Returns a string containing the supplied unsigned int 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 int values, possibly empty
  public static String join(String separatorint... 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 int values lexicographically. That is, it compares, using compare(int,int)), 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, [] < [1] < [1, 2] < [2] < [1 << 31].

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(int[],int[]).

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

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

Parameters:
dividend the dividend (numerator)
divisor the divisor (denominator)
Throws:
java.lang.ArithmeticException if divisor is 0
  public static int divide(int dividendint divisor) {
    return (int) (toLong(dividend) / toLong(divisor));
  }

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

Parameters:
dividend the dividend (numerator)
divisor the divisor (denominator)
Throws:
java.lang.ArithmeticException if divisor is 0
  public static int remainder(int dividendint divisor) {
    return (int) (toLong(dividend) % toLong(divisor));
  }

  
Returns the unsigned int 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 int value
Since:
13.0
  public static int decode(String stringValue) {
    ParseRequest request = ParseRequest.fromString(stringValue);
    try {
      return parseUnsignedInt(request.rawValuerequest.radix);
    } catch (NumberFormatException e) {
      NumberFormatException decodeException =
          new NumberFormatException("Error parsing value: " + stringValue);
      decodeException.initCause(e);
      throw decodeException;
    }
  }

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

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

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

Parameters:
string the string containing the unsigned integer representation to be parsed.
radix the radix to use while parsing s; must be between java.lang.Character.MIN_RADIX and java.lang.Character.MAX_RADIX.
Throws:
java.lang.NumberFormatException if the string does not contain a valid unsigned int, or if supplied radix is invalid.
java.lang.NullPointerException if s is null (in contrast to java.lang.Integer.parseInt(java.lang.String))
  public static int parseUnsignedInt(String stringint radix) {
    checkNotNull(string);
    long result = Long.parseLong(stringradix);
    if ((result & ) != result) {
      throw new NumberFormatException("Input " + string + " in base " + radix
          + " is not in the range of an unsigned integer");
    }
    return (intresult;
  }

  
Returns a string representation of x, where x is treated as unsigned.
  public static String toString(int 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(int xint radix) {
    long asLong = x & ;
    return Long.toString(asLongradix);
  }
New to GrepCode? Check out our FAQ X