001/* 002 * Copyright (C) 2011 The Guava Authors 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 005 * in compliance with the License. You may obtain a copy of the License at 006 * 007 * http://www.apache.org/licenses/LICENSE-2.0 008 * 009 * Unless required by applicable law or agreed to in writing, software distributed under the License 010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 011 * or implied. See the License for the specific language governing permissions and limitations under 012 * the License. 013 */ 014 015package com.google.common.primitives; 016 017import static com.google.common.base.Preconditions.checkArgument; 018import static com.google.common.base.Preconditions.checkNotNull; 019 020import com.google.common.annotations.Beta; 021import com.google.common.annotations.GwtCompatible; 022import com.google.errorprone.annotations.CanIgnoreReturnValue; 023import java.util.Arrays; 024import java.util.Comparator; 025 026/** 027 * Static utility methods pertaining to {@code int} primitives that interpret values as 028 * <i>unsigned</i> (that is, any negative value {@code x} is treated as the positive value 029 * {@code 2^32 + x}). The methods for which signedness is not an issue are in {@link Ints}, as well 030 * as signed versions of methods for which signedness is an issue. 031 * 032 * <p>In addition, this class provides several static methods for converting an {@code int} to a 033 * {@code String} and a {@code String} to an {@code int} that treat the {@code int} as an unsigned 034 * number. 035 * 036 * <p>Users of these utilities must be <i>extremely careful</i> not to mix up signed and unsigned 037 * {@code int} values. When possible, it is recommended that the {@link UnsignedInteger} wrapper 038 * class be used, at a small efficiency penalty, to enforce the distinction in the type system. 039 * 040 * <p>See the Guava User Guide article on 041 * <a href="https://github.com/google/guava/wiki/PrimitivesExplained#unsigned-support">unsigned 042 * primitive utilities</a>. 043 * 044 * @author Louis Wasserman 045 * @since 11.0 046 */ 047@Beta 048@GwtCompatible 049public final class UnsignedInts { 050 static final long INT_MASK = 0xffffffffL; 051 052 private UnsignedInts() {} 053 054 static int flip(int value) { 055 return value ^ Integer.MIN_VALUE; 056 } 057 058 /** 059 * Compares the two specified {@code int} values, treating them as unsigned values between 060 * {@code 0} and {@code 2^32 - 1} inclusive. 061 * 062 * @param a the first unsigned {@code int} to compare 063 * @param b the second unsigned {@code int} to compare 064 * @return a negative value if {@code a} is less than {@code b}; a positive value if {@code a} is 065 * greater than {@code b}; or zero if they are equal 066 */ 067 public static int compare(int a, int b) { 068 return Ints.compare(flip(a), flip(b)); 069 } 070 071 /** 072 * Returns the value of the given {@code int} as a {@code long}, when treated as unsigned. 073 */ 074 public static long toLong(int value) { 075 return value & INT_MASK; 076 } 077 078 /** 079 * Returns the least value present in {@code array}, treating values as unsigned. 080 * 081 * @param array a <i>nonempty</i> array of unsigned {@code int} values 082 * @return the value present in {@code array} that is less than or equal to every other value in 083 * the array according to {@link #compare} 084 * @throws IllegalArgumentException if {@code array} is empty 085 */ 086 public static int min(int... array) { 087 checkArgument(array.length > 0); 088 int min = flip(array[0]); 089 for (int i = 1; i < array.length; i++) { 090 int next = flip(array[i]); 091 if (next < min) { 092 min = next; 093 } 094 } 095 return flip(min); 096 } 097 098 /** 099 * Returns the greatest value present in {@code array}, treating values as unsigned. 100 * 101 * @param array a <i>nonempty</i> array of unsigned {@code int} values 102 * @return the value present in {@code array} that is greater than or equal to every other value 103 * in the array according to {@link #compare} 104 * @throws IllegalArgumentException if {@code array} is empty 105 */ 106 public static int max(int... array) { 107 checkArgument(array.length > 0); 108 int max = flip(array[0]); 109 for (int i = 1; i < array.length; i++) { 110 int next = flip(array[i]); 111 if (next > max) { 112 max = next; 113 } 114 } 115 return flip(max); 116 } 117 118 /** 119 * Returns a string containing the supplied unsigned {@code int} values separated by 120 * {@code separator}. For example, {@code join("-", 1, 2, 3)} returns the string {@code "1-2-3"}. 121 * 122 * @param separator the text that should appear between consecutive values in the resulting string 123 * (but not at the start or end) 124 * @param array an array of unsigned {@code int} values, possibly empty 125 */ 126 public static String join(String separator, int... array) { 127 checkNotNull(separator); 128 if (array.length == 0) { 129 return ""; 130 } 131 132 // For pre-sizing a builder, just get the right order of magnitude 133 StringBuilder builder = new StringBuilder(array.length * 5); 134 builder.append(toString(array[0])); 135 for (int i = 1; i < array.length; i++) { 136 builder.append(separator).append(toString(array[i])); 137 } 138 return builder.toString(); 139 } 140 141 /** 142 * Returns a comparator that compares two arrays of unsigned {@code int} values <a 143 * href="http://en.wikipedia.org/wiki/Lexicographical_order">lexicographically</a>. That is, it 144 * compares, using {@link #compare(int, int)}), the first pair of values that follow any common 145 * prefix, or when one array is a prefix of the other, treats the shorter array as the lesser. For 146 * example, {@code [] < [1] < [1, 2] < [2] < [1 << 31]}. 147 * 148 * <p>The returned comparator is inconsistent with {@link Object#equals(Object)} (since arrays 149 * support only identity equality), but it is consistent with {@link Arrays#equals(int[], int[])}. 150 */ 151 public static Comparator<int[]> lexicographicalComparator() { 152 return LexicographicalComparator.INSTANCE; 153 } 154 155 enum LexicographicalComparator implements Comparator<int[]> { 156 INSTANCE; 157 158 @Override 159 public int compare(int[] left, int[] right) { 160 int minLength = Math.min(left.length, right.length); 161 for (int i = 0; i < minLength; i++) { 162 if (left[i] != right[i]) { 163 return UnsignedInts.compare(left[i], right[i]); 164 } 165 } 166 return left.length - right.length; 167 } 168 169 @Override 170 public String toString() { 171 return "UnsignedInts.lexicographicalComparator()"; 172 } 173 } 174 175 /** 176 * Returns dividend / divisor, where the dividend and divisor are treated as unsigned 32-bit 177 * quantities. 178 * 179 * @param dividend the dividend (numerator) 180 * @param divisor the divisor (denominator) 181 * @throws ArithmeticException if divisor is 0 182 */ 183 public static int divide(int dividend, int divisor) { 184 return (int) (toLong(dividend) / toLong(divisor)); 185 } 186 187 /** 188 * Returns dividend % divisor, where the dividend and divisor are treated as unsigned 32-bit 189 * quantities. 190 * 191 * @param dividend the dividend (numerator) 192 * @param divisor the divisor (denominator) 193 * @throws ArithmeticException if divisor is 0 194 */ 195 public static int remainder(int dividend, int divisor) { 196 return (int) (toLong(dividend) % toLong(divisor)); 197 } 198 199 /** 200 * Returns the unsigned {@code int} value represented by the given string. 201 * 202 * Accepts a decimal, hexadecimal, or octal number given by specifying the following prefix: 203 * 204 * <ul> 205 * <li>{@code 0x}<i>HexDigits</i> 206 * <li>{@code 0X}<i>HexDigits</i> 207 * <li>{@code #}<i>HexDigits</i> 208 * <li>{@code 0}<i>OctalDigits</i> 209 * </ul> 210 * 211 * @throws NumberFormatException if the string does not contain a valid unsigned {@code int} value 212 * @since 13.0 213 */ 214 @CanIgnoreReturnValue 215 public static int decode(String stringValue) { 216 ParseRequest request = ParseRequest.fromString(stringValue); 217 218 try { 219 return parseUnsignedInt(request.rawValue, request.radix); 220 } catch (NumberFormatException e) { 221 NumberFormatException decodeException = 222 new NumberFormatException("Error parsing value: " + stringValue); 223 decodeException.initCause(e); 224 throw decodeException; 225 } 226 } 227 228 /** 229 * Returns the unsigned {@code int} value represented by the given decimal string. 230 * 231 * @throws NumberFormatException if the string does not contain a valid unsigned {@code int} value 232 * @throws NullPointerException if {@code s} is null (in contrast to 233 * {@link Integer#parseInt(String)}) 234 */ 235 @CanIgnoreReturnValue 236 public static int parseUnsignedInt(String s) { 237 return parseUnsignedInt(s, 10); 238 } 239 240 /** 241 * Returns the unsigned {@code int} value represented by a string with the given radix. 242 * 243 * @param string the string containing the unsigned integer representation to be parsed. 244 * @param radix the radix to use while parsing {@code s}; must be between 245 * {@link Character#MIN_RADIX} and {@link Character#MAX_RADIX}. 246 * @throws NumberFormatException if the string does not contain a valid unsigned {@code int}, or 247 * if supplied radix is invalid. 248 * @throws NullPointerException if {@code s} is null (in contrast to 249 * {@link Integer#parseInt(String)}) 250 */ 251 @CanIgnoreReturnValue 252 public static int parseUnsignedInt(String string, int radix) { 253 checkNotNull(string); 254 long result = Long.parseLong(string, radix); 255 if ((result & INT_MASK) != result) { 256 throw new NumberFormatException( 257 "Input " + string + " in base " + radix + " is not in the range of an unsigned integer"); 258 } 259 return (int) result; 260 } 261 262 /** 263 * Returns a string representation of x, where x is treated as unsigned. 264 */ 265 public static String toString(int x) { 266 return toString(x, 10); 267 } 268 269 /** 270 * Returns a string representation of {@code x} for the given radix, where {@code x} is treated as 271 * unsigned. 272 * 273 * @param x the value to convert to a string. 274 * @param radix the radix to use while working with {@code x} 275 * @throws IllegalArgumentException if {@code radix} is not between {@link Character#MIN_RADIX} 276 * and {@link Character#MAX_RADIX}. 277 */ 278 public static String toString(int x, int radix) { 279 long asLong = x & INT_MASK; 280 return Long.toString(asLong, radix); 281 } 282}