1 /* 2 * Copyright (C) 2014 The Android Open Source Project 3 * Copyright (c) 1994, 2013, Oracle and/or its affiliates. All rights reserved. 4 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 5 * 6 * This code is free software; you can redistribute it and/or modify it 7 * under the terms of the GNU General Public License version 2 only, as 8 * published by the Free Software Foundation. Oracle designates this 9 * particular file as subject to the "Classpath" exception as provided 10 * by Oracle in the LICENSE file that accompanied this code. 11 * 12 * This code is distributed in the hope that it will be useful, but WITHOUT 13 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 14 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 15 * version 2 for more details (a copy is included in the LICENSE file that 16 * accompanied this code). 17 * 18 * You should have received a copy of the GNU General Public License version 19 * 2 along with this work; if not, write to the Free Software Foundation, 20 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 21 * 22 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 23 * or visit www.oracle.com if you need additional information or have any 24 * questions. 25 */ 26 27 package java.lang; 28 29 import java.lang.annotation.Native; 30 31 /** 32 * The {@code Integer} class wraps a value of the primitive type 33 * {@code int} in an object. An object of type {@code Integer} 34 * contains a single field whose type is {@code int}. 35 * 36 * <p>In addition, this class provides several methods for converting 37 * an {@code int} to a {@code String} and a {@code String} to an 38 * {@code int}, as well as other constants and methods useful when 39 * dealing with an {@code int}. 40 * 41 * <p>Implementation note: The implementations of the "bit twiddling" 42 * methods (such as {@link #highestOneBit(int) highestOneBit} and 43 * {@link #numberOfTrailingZeros(int) numberOfTrailingZeros}) are 44 * based on material from Henry S. Warren, Jr.'s <i>Hacker's 45 * Delight</i>, (Addison Wesley, 2002). 46 * 47 * @author Lee Boynton 48 * @author Arthur van Hoff 49 * @author Josh Bloch 50 * @author Joseph D. Darcy 51 * @since JDK1.0 52 */ 53 public final class Integer extends Number implements Comparable<Integer> { 54 /** 55 * A constant holding the minimum value an {@code int} can 56 * have, -2<sup>31</sup>. 57 */ 58 @Native public static final int MIN_VALUE = 0x80000000; 59 60 /** 61 * A constant holding the maximum value an {@code int} can 62 * have, 2<sup>31</sup>-1. 63 */ 64 @Native public static final int MAX_VALUE = 0x7fffffff; 65 66 /** 67 * The {@code Class} instance representing the primitive type 68 * {@code int}. 69 * 70 * @since JDK1.1 71 */ 72 @SuppressWarnings("unchecked") 73 public static final Class<Integer> TYPE = (Class<Integer>) Class.getPrimitiveClass("int"); 74 75 /** 76 * All possible chars for representing a number as a String 77 */ 78 final static char[] digits = { 79 '0' , '1' , '2' , '3' , '4' , '5' , 80 '6' , '7' , '8' , '9' , 'a' , 'b' , 81 'c' , 'd' , 'e' , 'f' , 'g' , 'h' , 82 'i' , 'j' , 'k' , 'l' , 'm' , 'n' , 83 'o' , 'p' , 'q' , 'r' , 's' , 't' , 84 'u' , 'v' , 'w' , 'x' , 'y' , 'z' 85 }; 86 87 /** 88 * Returns a string representation of the first argument in the 89 * radix specified by the second argument. 90 * 91 * <p>If the radix is smaller than {@code Character.MIN_RADIX} 92 * or larger than {@code Character.MAX_RADIX}, then the radix 93 * {@code 10} is used instead. 94 * 95 * <p>If the first argument is negative, the first element of the 96 * result is the ASCII minus character {@code '-'} 97 * ({@code '\u005Cu002D'}). If the first argument is not 98 * negative, no sign character appears in the result. 99 * 100 * <p>The remaining characters of the result represent the magnitude 101 * of the first argument. If the magnitude is zero, it is 102 * represented by a single zero character {@code '0'} 103 * ({@code '\u005Cu0030'}); otherwise, the first character of 104 * the representation of the magnitude will not be the zero 105 * character. The following ASCII characters are used as digits: 106 * 107 * <blockquote> 108 * {@code 0123456789abcdefghijklmnopqrstuvwxyz} 109 * </blockquote> 110 * 111 * These are {@code '\u005Cu0030'} through 112 * {@code '\u005Cu0039'} and {@code '\u005Cu0061'} through 113 * {@code '\u005Cu007A'}. If {@code radix} is 114 * <var>N</var>, then the first <var>N</var> of these characters 115 * are used as radix-<var>N</var> digits in the order shown. Thus, 116 * the digits for hexadecimal (radix 16) are 117 * {@code 0123456789abcdef}. If uppercase letters are 118 * desired, the {@link java.lang.String#toUpperCase()} method may 119 * be called on the result: 120 * 121 * <blockquote> 122 * {@code Integer.toString(n, 16).toUpperCase()} 123 * </blockquote> 124 * 125 * @param i an integer to be converted to a string. 126 * @param radix the radix to use in the string representation. 127 * @return a string representation of the argument in the specified radix. 128 * @see java.lang.Character#MAX_RADIX 129 * @see java.lang.Character#MIN_RADIX 130 */ toString(int i, int radix)131 public static String toString(int i, int radix) { 132 if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX) 133 radix = 10; 134 135 /* Use the faster version */ 136 if (radix == 10) { 137 return toString(i); 138 } 139 140 char buf[] = new char[33]; 141 boolean negative = (i < 0); 142 int charPos = 32; 143 144 if (!negative) { 145 i = -i; 146 } 147 148 while (i <= -radix) { 149 buf[charPos--] = digits[-(i % radix)]; 150 i = i / radix; 151 } 152 buf[charPos] = digits[-i]; 153 154 if (negative) { 155 buf[--charPos] = '-'; 156 } 157 158 return new String(buf, charPos, (33 - charPos)); 159 } 160 161 /** 162 * Returns a string representation of the first argument as an 163 * unsigned integer value in the radix specified by the second 164 * argument. 165 * 166 * <p>If the radix is smaller than {@code Character.MIN_RADIX} 167 * or larger than {@code Character.MAX_RADIX}, then the radix 168 * {@code 10} is used instead. 169 * 170 * <p>Note that since the first argument is treated as an unsigned 171 * value, no leading sign character is printed. 172 * 173 * <p>If the magnitude is zero, it is represented by a single zero 174 * character {@code '0'} ({@code '\u005Cu0030'}); otherwise, 175 * the first character of the representation of the magnitude will 176 * not be the zero character. 177 * 178 * <p>The behavior of radixes and the characters used as digits 179 * are the same as {@link #toString(int, int) toString}. 180 * 181 * @param i an integer to be converted to an unsigned string. 182 * @param radix the radix to use in the string representation. 183 * @return an unsigned string representation of the argument in the specified radix. 184 * @see #toString(int, int) 185 * @since 1.8 186 */ toUnsignedString(int i, int radix)187 public static String toUnsignedString(int i, int radix) { 188 return Long.toUnsignedString(toUnsignedLong(i), radix); 189 } 190 191 /** 192 * Returns a string representation of the integer argument as an 193 * unsigned integer in base 16. 194 * 195 * <p>The unsigned integer value is the argument plus 2<sup>32</sup> 196 * if the argument is negative; otherwise, it is equal to the 197 * argument. This value is converted to a string of ASCII digits 198 * in hexadecimal (base 16) with no extra leading 199 * {@code 0}s. 200 * 201 * <p>The value of the argument can be recovered from the returned 202 * string {@code s} by calling {@link 203 * Integer#parseUnsignedInt(String, int) 204 * Integer.parseUnsignedInt(s, 16)}. 205 * 206 * <p>If the unsigned magnitude is zero, it is represented by a 207 * single zero character {@code '0'} ({@code '\u005Cu0030'}); 208 * otherwise, the first character of the representation of the 209 * unsigned magnitude will not be the zero character. The 210 * following characters are used as hexadecimal digits: 211 * 212 * <blockquote> 213 * {@code 0123456789abcdef} 214 * </blockquote> 215 * 216 * These are the characters {@code '\u005Cu0030'} through 217 * {@code '\u005Cu0039'} and {@code '\u005Cu0061'} through 218 * {@code '\u005Cu0066'}. If uppercase letters are 219 * desired, the {@link java.lang.String#toUpperCase()} method may 220 * be called on the result: 221 * 222 * <blockquote> 223 * {@code Integer.toHexString(n).toUpperCase()} 224 * </blockquote> 225 * 226 * @param i an integer to be converted to a string. 227 * @return the string representation of the unsigned integer value 228 * represented by the argument in hexadecimal (base 16). 229 * @see #parseUnsignedInt(String, int) 230 * @see #toUnsignedString(int, int) 231 * @since JDK1.0.2 232 */ toHexString(int i)233 public static String toHexString(int i) { 234 return toUnsignedString0(i, 4); 235 } 236 237 /** 238 * Returns a string representation of the integer argument as an 239 * unsigned integer in base 8. 240 * 241 * <p>The unsigned integer value is the argument plus 2<sup>32</sup> 242 * if the argument is negative; otherwise, it is equal to the 243 * argument. This value is converted to a string of ASCII digits 244 * in octal (base 8) with no extra leading {@code 0}s. 245 * 246 * <p>The value of the argument can be recovered from the returned 247 * string {@code s} by calling {@link 248 * Integer#parseUnsignedInt(String, int) 249 * Integer.parseUnsignedInt(s, 8)}. 250 * 251 * <p>If the unsigned magnitude is zero, it is represented by a 252 * single zero character {@code '0'} ({@code '\u005Cu0030'}); 253 * otherwise, the first character of the representation of the 254 * unsigned magnitude will not be the zero character. The 255 * following characters are used as octal digits: 256 * 257 * <blockquote> 258 * {@code 01234567} 259 * </blockquote> 260 * 261 * These are the characters {@code '\u005Cu0030'} through 262 * {@code '\u005Cu0037'}. 263 * 264 * @param i an integer to be converted to a string. 265 * @return the string representation of the unsigned integer value 266 * represented by the argument in octal (base 8). 267 * @see #parseUnsignedInt(String, int) 268 * @see #toUnsignedString(int, int) 269 * @since JDK1.0.2 270 */ toOctalString(int i)271 public static String toOctalString(int i) { 272 return toUnsignedString0(i, 3); 273 } 274 275 /** 276 * Returns a string representation of the integer argument as an 277 * unsigned integer in base 2. 278 * 279 * <p>The unsigned integer value is the argument plus 2<sup>32</sup> 280 * if the argument is negative; otherwise it is equal to the 281 * argument. This value is converted to a string of ASCII digits 282 * in binary (base 2) with no extra leading {@code 0}s. 283 * 284 * <p>The value of the argument can be recovered from the returned 285 * string {@code s} by calling {@link 286 * Integer#parseUnsignedInt(String, int) 287 * Integer.parseUnsignedInt(s, 2)}. 288 * 289 * <p>If the unsigned magnitude is zero, it is represented by a 290 * single zero character {@code '0'} ({@code '\u005Cu0030'}); 291 * otherwise, the first character of the representation of the 292 * unsigned magnitude will not be the zero character. The 293 * characters {@code '0'} ({@code '\u005Cu0030'}) and {@code 294 * '1'} ({@code '\u005Cu0031'}) are used as binary digits. 295 * 296 * @param i an integer to be converted to a string. 297 * @return the string representation of the unsigned integer value 298 * represented by the argument in binary (base 2). 299 * @see #parseUnsignedInt(String, int) 300 * @see #toUnsignedString(int, int) 301 * @since JDK1.0.2 302 */ toBinaryString(int i)303 public static String toBinaryString(int i) { 304 return toUnsignedString0(i, 1); 305 } 306 307 /** 308 * Convert the integer to an unsigned number. 309 */ toUnsignedString0(int val, int shift)310 private static String toUnsignedString0(int val, int shift) { 311 // assert shift > 0 && shift <=5 : "Illegal shift value"; 312 int mag = Integer.SIZE - Integer.numberOfLeadingZeros(val); 313 int chars = Math.max(((mag + (shift - 1)) / shift), 1); 314 char[] buf = new char[chars]; 315 316 formatUnsignedInt(val, shift, buf, 0, chars); 317 318 // Android-changed: Use regular constructor instead of one which takes over "buf". 319 // return new String(buf, true); 320 return new String(buf); 321 } 322 323 /** 324 * Format a long (treated as unsigned) into a character buffer. 325 * @param val the unsigned int to format 326 * @param shift the log2 of the base to format in (4 for hex, 3 for octal, 1 for binary) 327 * @param buf the character buffer to write to 328 * @param offset the offset in the destination buffer to start at 329 * @param len the number of characters to write 330 * @return the lowest character location used 331 */ formatUnsignedInt(int val, int shift, char[] buf, int offset, int len)332 static int formatUnsignedInt(int val, int shift, char[] buf, int offset, int len) { 333 int charPos = len; 334 int radix = 1 << shift; 335 int mask = radix - 1; 336 do { 337 buf[offset + --charPos] = Integer.digits[val & mask]; 338 val >>>= shift; 339 } while (val != 0 && charPos > 0); 340 341 return charPos; 342 } 343 344 // BEGIN Android-changed: Cache the toString() result for small values. 345 private static final String[] SMALL_NEG_VALUES = new String[100]; 346 private static final String[] SMALL_NONNEG_VALUES = new String[100]; 347 // END Android-changed: Cache the toString() result for small values. 348 349 final static char [] DigitTens = { 350 '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', 351 '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', 352 '2', '2', '2', '2', '2', '2', '2', '2', '2', '2', 353 '3', '3', '3', '3', '3', '3', '3', '3', '3', '3', 354 '4', '4', '4', '4', '4', '4', '4', '4', '4', '4', 355 '5', '5', '5', '5', '5', '5', '5', '5', '5', '5', 356 '6', '6', '6', '6', '6', '6', '6', '6', '6', '6', 357 '7', '7', '7', '7', '7', '7', '7', '7', '7', '7', 358 '8', '8', '8', '8', '8', '8', '8', '8', '8', '8', 359 '9', '9', '9', '9', '9', '9', '9', '9', '9', '9', 360 } ; 361 362 final static char [] DigitOnes = { 363 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 364 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 365 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 366 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 367 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 368 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 369 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 370 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 371 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 372 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 373 } ; 374 375 // I use the "invariant division by multiplication" trick to 376 // accelerate Integer.toString. In particular we want to 377 // avoid division by 10. 378 // 379 // The "trick" has roughly the same performance characteristics 380 // as the "classic" Integer.toString code on a non-JIT VM. 381 // The trick avoids .rem and .div calls but has a longer code 382 // path and is thus dominated by dispatch overhead. In the 383 // JIT case the dispatch overhead doesn't exist and the 384 // "trick" is considerably faster than the classic code. 385 // 386 // TODO-FIXME: convert (x * 52429) into the equiv shift-add 387 // sequence. 388 // 389 // RE: Division by Invariant Integers using Multiplication 390 // T Gralund, P Montgomery 391 // ACM PLDI 1994 392 // 393 394 /** 395 * Returns a {@code String} object representing the 396 * specified integer. The argument is converted to signed decimal 397 * representation and returned as a string, exactly as if the 398 * argument and radix 10 were given as arguments to the {@link 399 * #toString(int, int)} method. 400 * 401 * @param i an integer to be converted. 402 * @return a string representation of the argument in base 10. 403 */ toString(int i)404 public static String toString(int i) { 405 if (i == Integer.MIN_VALUE) 406 return "-2147483648"; 407 408 // BEGIN Android-changed: Cache the String for small values. 409 // int size = (i < 0) ? stringSize(-i) + 1 : stringSize(i); 410 boolean negative = i < 0; 411 boolean small = negative ? i > -100 : i < 100; 412 if (small) { 413 final String[] smallValues = negative ? SMALL_NEG_VALUES : SMALL_NONNEG_VALUES; 414 415 if (negative) { 416 i = -i; 417 if (smallValues[i] == null) { 418 smallValues[i] = 419 i < 10 ? new String(new char[]{'-', DigitOnes[i]}) 420 : new String(new char[]{'-', DigitTens[i], DigitOnes[i]}); 421 } 422 } else { 423 if (smallValues[i] == null) { 424 smallValues[i] = 425 i < 10 ? new String(new char[]{DigitOnes[i]}) 426 : new String(new char[]{DigitTens[i], DigitOnes[i]}); 427 } 428 } 429 return smallValues[i]; 430 } 431 int size = negative ? stringSize(-i) + 1 : stringSize(i); 432 // END Android-changed: Cache the String for small values. 433 char[] buf = new char[size]; 434 getChars(i, size, buf); 435 // Android-changed: Use regular constructor instead of one which takes over "buf". 436 // return new String(buf, true); 437 return new String(buf); 438 } 439 440 /** 441 * Returns a string representation of the argument as an unsigned 442 * decimal value. 443 * 444 * The argument is converted to unsigned decimal representation 445 * and returned as a string exactly as if the argument and radix 446 * 10 were given as arguments to the {@link #toUnsignedString(int, 447 * int)} method. 448 * 449 * @param i an integer to be converted to an unsigned string. 450 * @return an unsigned string representation of the argument. 451 * @see #toUnsignedString(int, int) 452 * @since 1.8 453 */ 454 public static String toUnsignedString(int i) { 455 return Long.toString(toUnsignedLong(i)); 456 } 457 458 /** 459 * Places characters representing the integer i into the 460 * character array buf. The characters are placed into 461 * the buffer backwards starting with the least significant 462 * digit at the specified index (exclusive), and working 463 * backwards from there. 464 * 465 * Will fail if i == Integer.MIN_VALUE 466 */ 467 static void getChars(int i, int index, char[] buf) { 468 int q, r; 469 int charPos = index; 470 char sign = 0; 471 472 if (i < 0) { 473 sign = '-'; 474 i = -i; 475 } 476 477 // Generate two digits per iteration 478 while (i >= 65536) { 479 q = i / 100; 480 // really: r = i - (q * 100); 481 r = i - ((q << 6) + (q << 5) + (q << 2)); 482 i = q; 483 buf [--charPos] = DigitOnes[r]; 484 buf [--charPos] = DigitTens[r]; 485 } 486 487 // Fall thru to fast mode for smaller numbers 488 // assert(i <= 65536, i); 489 for (;;) { 490 q = (i * 52429) >>> (16+3); 491 r = i - ((q << 3) + (q << 1)); // r = i-(q*10) ... 492 buf [--charPos] = digits [r]; 493 i = q; 494 if (i == 0) break; 495 } 496 if (sign != 0) { 497 buf [--charPos] = sign; 498 } 499 } 500 501 final static int [] sizeTable = { 9, 99, 999, 9999, 99999, 999999, 9999999, 502 99999999, 999999999, Integer.MAX_VALUE }; 503 504 // Requires positive x 505 static int stringSize(int x) { 506 for (int i=0; ; i++) 507 if (x <= sizeTable[i]) 508 return i+1; 509 } 510 511 /** 512 * Parses the string argument as a signed integer in the radix 513 * specified by the second argument. The characters in the string 514 * must all be digits of the specified radix (as determined by 515 * whether {@link java.lang.Character#digit(char, int)} returns a 516 * nonnegative value), except that the first character may be an 517 * ASCII minus sign {@code '-'} ({@code '\u005Cu002D'}) to 518 * indicate a negative value or an ASCII plus sign {@code '+'} 519 * ({@code '\u005Cu002B'}) to indicate a positive value. The 520 * resulting integer value is returned. 521 * 522 * <p>An exception of type {@code NumberFormatException} is 523 * thrown if any of the following situations occurs: 524 * <ul> 525 * <li>The first argument is {@code null} or is a string of 526 * length zero. 527 * 528 * <li>The radix is either smaller than 529 * {@link java.lang.Character#MIN_RADIX} or 530 * larger than {@link java.lang.Character#MAX_RADIX}. 531 * 532 * <li>Any character of the string is not a digit of the specified 533 * radix, except that the first character may be a minus sign 534 * {@code '-'} ({@code '\u005Cu002D'}) or plus sign 535 * {@code '+'} ({@code '\u005Cu002B'}) provided that the 536 * string is longer than length 1. 537 * 538 * <li>The value represented by the string is not a value of type 539 * {@code int}. 540 * </ul> 541 * 542 * <p>Examples: 543 * <blockquote><pre> 544 * parseInt("0", 10) returns 0 545 * parseInt("473", 10) returns 473 546 * parseInt("+42", 10) returns 42 547 * parseInt("-0", 10) returns 0 548 * parseInt("-FF", 16) returns -255 549 * parseInt("1100110", 2) returns 102 550 * parseInt("2147483647", 10) returns 2147483647 551 * parseInt("-2147483648", 10) returns -2147483648 552 * parseInt("2147483648", 10) throws a NumberFormatException 553 * parseInt("99", 8) throws a NumberFormatException 554 * parseInt("Kona", 10) throws a NumberFormatException 555 * parseInt("Kona", 27) returns 411787 556 * </pre></blockquote> 557 * 558 * @param s the {@code String} containing the integer 559 * representation to be parsed 560 * @param radix the radix to be used while parsing {@code s}. 561 * @return the integer represented by the string argument in the 562 * specified radix. 563 * @exception NumberFormatException if the {@code String} 564 * does not contain a parsable {@code int}. 565 */ 566 public static int parseInt(String s, int radix) 567 throws NumberFormatException 568 { 569 /* 570 * WARNING: This method may be invoked early during VM initialization 571 * before IntegerCache is initialized. Care must be taken to not use 572 * the valueOf method. 573 */ 574 575 if (s == null) { 576 // Android-changed: Improve exception message for parseInt. 577 throw new NumberFormatException("s == null"); 578 } 579 580 if (radix < Character.MIN_RADIX) { 581 throw new NumberFormatException("radix " + radix + 582 " less than Character.MIN_RADIX"); 583 } 584 585 if (radix > Character.MAX_RADIX) { 586 throw new NumberFormatException("radix " + radix + 587 " greater than Character.MAX_RADIX"); 588 } 589 590 int result = 0; 591 boolean negative = false; 592 int i = 0, len = s.length(); 593 int limit = -Integer.MAX_VALUE; 594 int multmin; 595 int digit; 596 597 if (len > 0) { 598 char firstChar = s.charAt(0); 599 if (firstChar < '0') { // Possible leading "+" or "-" 600 if (firstChar == '-') { 601 negative = true; 602 limit = Integer.MIN_VALUE; 603 } else if (firstChar != '+') 604 throw NumberFormatException.forInputString(s); 605 606 if (len == 1) // Cannot have lone "+" or "-" 607 throw NumberFormatException.forInputString(s); 608 i++; 609 } 610 multmin = limit / radix; 611 while (i < len) { 612 // Accumulating negatively avoids surprises near MAX_VALUE 613 digit = Character.digit(s.charAt(i++),radix); 614 if (digit < 0) { 615 throw NumberFormatException.forInputString(s); 616 } 617 if (result < multmin) { 618 throw NumberFormatException.forInputString(s); 619 } 620 result *= radix; 621 if (result < limit + digit) { 622 throw NumberFormatException.forInputString(s); 623 } 624 result -= digit; 625 } 626 } else { 627 throw NumberFormatException.forInputString(s); 628 } 629 return negative ? result : -result; 630 } 631 632 /** 633 * Parses the string argument as a signed decimal integer. The 634 * characters in the string must all be decimal digits, except 635 * that the first character may be an ASCII minus sign {@code '-'} 636 * ({@code '\u005Cu002D'}) to indicate a negative value or an 637 * ASCII plus sign {@code '+'} ({@code '\u005Cu002B'}) to 638 * indicate a positive value. The resulting integer value is 639 * returned, exactly as if the argument and the radix 10 were 640 * given as arguments to the {@link #parseInt(java.lang.String, 641 * int)} method. 642 * 643 * @param s a {@code String} containing the {@code int} 644 * representation to be parsed 645 * @return the integer value represented by the argument in decimal. 646 * @exception NumberFormatException if the string does not contain a 647 * parsable integer. 648 */ 649 public static int parseInt(String s) throws NumberFormatException { 650 return parseInt(s,10); 651 } 652 653 /** 654 * Parses the string argument as an unsigned integer in the radix 655 * specified by the second argument. An unsigned integer maps the 656 * values usually associated with negative numbers to positive 657 * numbers larger than {@code MAX_VALUE}. 658 * 659 * The characters in the string must all be digits of the 660 * specified radix (as determined by whether {@link 661 * java.lang.Character#digit(char, int)} returns a nonnegative 662 * value), except that the first character may be an ASCII plus 663 * sign {@code '+'} ({@code '\u005Cu002B'}). The resulting 664 * integer value is returned. 665 * 666 * <p>An exception of type {@code NumberFormatException} is 667 * thrown if any of the following situations occurs: 668 * <ul> 669 * <li>The first argument is {@code null} or is a string of 670 * length zero. 671 * 672 * <li>The radix is either smaller than 673 * {@link java.lang.Character#MIN_RADIX} or 674 * larger than {@link java.lang.Character#MAX_RADIX}. 675 * 676 * <li>Any character of the string is not a digit of the specified 677 * radix, except that the first character may be a plus sign 678 * {@code '+'} ({@code '\u005Cu002B'}) provided that the 679 * string is longer than length 1. 680 * 681 * <li>The value represented by the string is larger than the 682 * largest unsigned {@code int}, 2<sup>32</sup>-1. 683 * 684 * </ul> 685 * 686 * 687 * @param s the {@code String} containing the unsigned integer 688 * representation to be parsed 689 * @param radix the radix to be used while parsing {@code s}. 690 * @return the integer represented by the string argument in the 691 * specified radix. 692 * @throws NumberFormatException if the {@code String} 693 * does not contain a parsable {@code int}. 694 * @since 1.8 695 */ 696 public static int parseUnsignedInt(String s, int radix) 697 throws NumberFormatException { 698 if (s == null) { 699 throw new NumberFormatException("null"); 700 } 701 702 int len = s.length(); 703 if (len > 0) { 704 char firstChar = s.charAt(0); 705 if (firstChar == '-') { 706 throw new 707 NumberFormatException(String.format("Illegal leading minus sign " + 708 "on unsigned string %s.", s)); 709 } else { 710 if (len <= 5 || // Integer.MAX_VALUE in Character.MAX_RADIX is 6 digits 711 (radix == 10 && len <= 9) ) { // Integer.MAX_VALUE in base 10 is 10 digits 712 return parseInt(s, radix); 713 } else { 714 long ell = Long.parseLong(s, radix); 715 if ((ell & 0xffff_ffff_0000_0000L) == 0) { 716 return (int) ell; 717 } else { 718 throw new 719 NumberFormatException(String.format("String value %s exceeds " + 720 "range of unsigned int.", s)); 721 } 722 } 723 } 724 } else { 725 throw NumberFormatException.forInputString(s); 726 } 727 } 728 729 /** 730 * Parses the string argument as an unsigned decimal integer. The 731 * characters in the string must all be decimal digits, except 732 * that the first character may be an an ASCII plus sign {@code 733 * '+'} ({@code '\u005Cu002B'}). The resulting integer value 734 * is returned, exactly as if the argument and the radix 10 were 735 * given as arguments to the {@link 736 * #parseUnsignedInt(java.lang.String, int)} method. 737 * 738 * @param s a {@code String} containing the unsigned {@code int} 739 * representation to be parsed 740 * @return the unsigned integer value represented by the argument in decimal. 741 * @throws NumberFormatException if the string does not contain a 742 * parsable unsigned integer. 743 * @since 1.8 744 */ 745 public static int parseUnsignedInt(String s) throws NumberFormatException { 746 return parseUnsignedInt(s, 10); 747 } 748 749 /** 750 * Returns an {@code Integer} object holding the value 751 * extracted from the specified {@code String} when parsed 752 * with the radix given by the second argument. The first argument 753 * is interpreted as representing a signed integer in the radix 754 * specified by the second argument, exactly as if the arguments 755 * were given to the {@link #parseInt(java.lang.String, int)} 756 * method. The result is an {@code Integer} object that 757 * represents the integer value specified by the string. 758 * 759 * <p>In other words, this method returns an {@code Integer} 760 * object equal to the value of: 761 * 762 * <blockquote> 763 * {@code new Integer(Integer.parseInt(s, radix))} 764 * </blockquote> 765 * 766 * @param s the string to be parsed. 767 * @param radix the radix to be used in interpreting {@code s} 768 * @return an {@code Integer} object holding the value 769 * represented by the string argument in the specified 770 * radix. 771 * @exception NumberFormatException if the {@code String} 772 * does not contain a parsable {@code int}. 773 */ 774 public static Integer valueOf(String s, int radix) throws NumberFormatException { 775 return Integer.valueOf(parseInt(s,radix)); 776 } 777 778 /** 779 * Returns an {@code Integer} object holding the 780 * value of the specified {@code String}. The argument is 781 * interpreted as representing a signed decimal integer, exactly 782 * as if the argument were given to the {@link 783 * #parseInt(java.lang.String)} method. The result is an 784 * {@code Integer} object that represents the integer value 785 * specified by the string. 786 * 787 * <p>In other words, this method returns an {@code Integer} 788 * object equal to the value of: 789 * 790 * <blockquote> 791 * {@code new Integer(Integer.parseInt(s))} 792 * </blockquote> 793 * 794 * @param s the string to be parsed. 795 * @return an {@code Integer} object holding the value 796 * represented by the string argument. 797 * @exception NumberFormatException if the string cannot be parsed 798 * as an integer. 799 */ 800 public static Integer valueOf(String s) throws NumberFormatException { 801 return Integer.valueOf(parseInt(s, 10)); 802 } 803 804 /** 805 * Cache to support the object identity semantics of autoboxing for values between 806 * -128 and 127 (inclusive) as required by JLS. 807 * 808 * The cache is initialized on first usage. The size of the cache 809 * may be controlled by the {@code -XX:AutoBoxCacheMax=<size>} option. 810 * During VM initialization, java.lang.Integer.IntegerCache.high property 811 * may be set and saved in the private system properties in the 812 * sun.misc.VM class. 813 */ 814 815 private static class IntegerCache { 816 static final int low = -128; 817 static final int high; 818 static final Integer cache[]; 819 820 static { 821 // high value may be configured by property 822 int h = 127; 823 String integerCacheHighPropValue = 824 sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high"); 825 if (integerCacheHighPropValue != null) { 826 try { 827 int i = parseInt(integerCacheHighPropValue); 828 i = Math.max(i, 127); 829 // Maximum array size is Integer.MAX_VALUE 830 h = Math.min(i, Integer.MAX_VALUE - (-low) -1); 831 } catch( NumberFormatException nfe) { 832 // If the property cannot be parsed into an int, ignore it. 833 } 834 } 835 high = h; 836 837 cache = new Integer[(high - low) + 1]; 838 int j = low; 839 for(int k = 0; k < cache.length; k++) 840 cache[k] = new Integer(j++); 841 842 // range [-128, 127] must be interned (JLS7 5.1.7) 843 assert IntegerCache.high >= 127; 844 } 845 846 private IntegerCache() {} 847 } 848 849 /** 850 * Returns an {@code Integer} instance representing the specified 851 * {@code int} value. If a new {@code Integer} instance is not 852 * required, this method should generally be used in preference to 853 * the constructor {@link #Integer(int)}, as this method is likely 854 * to yield significantly better space and time performance by 855 * caching frequently requested values. 856 * 857 * This method will always cache values in the range -128 to 127, 858 * inclusive, and may cache other values outside of this range. 859 * 860 * @param i an {@code int} value. 861 * @return an {@code Integer} instance representing {@code i}. 862 * @since 1.5 863 */ 864 public static Integer valueOf(int i) { 865 if (i >= IntegerCache.low && i <= IntegerCache.high) 866 return IntegerCache.cache[i + (-IntegerCache.low)]; 867 return new Integer(i); 868 } 869 870 /** 871 * The value of the {@code Integer}. 872 * 873 * @serial 874 */ 875 private final int value; 876 877 /** 878 * Constructs a newly allocated {@code Integer} object that 879 * represents the specified {@code int} value. 880 * 881 * @param value the value to be represented by the 882 * {@code Integer} object. 883 */ 884 public Integer(int value) { 885 this.value = value; 886 } 887 888 /** 889 * Constructs a newly allocated {@code Integer} object that 890 * represents the {@code int} value indicated by the 891 * {@code String} parameter. The string is converted to an 892 * {@code int} value in exactly the manner used by the 893 * {@code parseInt} method for radix 10. 894 * 895 * @param s the {@code String} to be converted to an 896 * {@code Integer}. 897 * @exception NumberFormatException if the {@code String} does not 898 * contain a parsable integer. 899 * @see java.lang.Integer#parseInt(java.lang.String, int) 900 */ 901 public Integer(String s) throws NumberFormatException { 902 this.value = parseInt(s, 10); 903 } 904 905 /** 906 * Returns the value of this {@code Integer} as a {@code byte} 907 * after a narrowing primitive conversion. 908 * @jls 5.1.3 Narrowing Primitive Conversions 909 */ 910 public byte byteValue() { 911 return (byte)value; 912 } 913 914 /** 915 * Returns the value of this {@code Integer} as a {@code short} 916 * after a narrowing primitive conversion. 917 * @jls 5.1.3 Narrowing Primitive Conversions 918 */ 919 public short shortValue() { 920 return (short)value; 921 } 922 923 /** 924 * Returns the value of this {@code Integer} as an 925 * {@code int}. 926 */ 927 public int intValue() { 928 return value; 929 } 930 931 /** 932 * Returns the value of this {@code Integer} as a {@code long} 933 * after a widening primitive conversion. 934 * @jls 5.1.2 Widening Primitive Conversions 935 * @see Integer#toUnsignedLong(int) 936 */ 937 public long longValue() { 938 return (long)value; 939 } 940 941 /** 942 * Returns the value of this {@code Integer} as a {@code float} 943 * after a widening primitive conversion. 944 * @jls 5.1.2 Widening Primitive Conversions 945 */ 946 public float floatValue() { 947 return (float)value; 948 } 949 950 /** 951 * Returns the value of this {@code Integer} as a {@code double} 952 * after a widening primitive conversion. 953 * @jls 5.1.2 Widening Primitive Conversions 954 */ 955 public double doubleValue() { 956 return (double)value; 957 } 958 959 /** 960 * Returns a {@code String} object representing this 961 * {@code Integer}'s value. The value is converted to signed 962 * decimal representation and returned as a string, exactly as if 963 * the integer value were given as an argument to the {@link 964 * java.lang.Integer#toString(int)} method. 965 * 966 * @return a string representation of the value of this object in 967 * base 10. 968 */ 969 public String toString() { 970 return toString(value); 971 } 972 973 /** 974 * Returns a hash code for this {@code Integer}. 975 * 976 * @return a hash code value for this object, equal to the 977 * primitive {@code int} value represented by this 978 * {@code Integer} object. 979 */ 980 @Override 981 public int hashCode() { 982 return Integer.hashCode(value); 983 } 984 985 /** 986 * Returns a hash code for a {@code int} value; compatible with 987 * {@code Integer.hashCode()}. 988 * 989 * @param value the value to hash 990 * @since 1.8 991 * 992 * @return a hash code value for a {@code int} value. 993 */ 994 public static int hashCode(int value) { 995 return value; 996 } 997 998 /** 999 * Compares this object to the specified object. The result is 1000 * {@code true} if and only if the argument is not 1001 * {@code null} and is an {@code Integer} object that 1002 * contains the same {@code int} value as this object. 1003 * 1004 * @param obj the object to compare with. 1005 * @return {@code true} if the objects are the same; 1006 * {@code false} otherwise. 1007 */ 1008 public boolean equals(Object obj) { 1009 if (obj instanceof Integer) { 1010 return value == ((Integer)obj).intValue(); 1011 } 1012 return false; 1013 } 1014 1015 /** 1016 * Determines the integer value of the system property with the 1017 * specified name. 1018 * 1019 * <p>The first argument is treated as the name of a system 1020 * property. System properties are accessible through the {@link 1021 * java.lang.System#getProperty(java.lang.String)} method. The 1022 * string value of this property is then interpreted as an integer 1023 * value using the grammar supported by {@link Integer#decode decode} and 1024 * an {@code Integer} object representing this value is returned. 1025 * 1026 * <p>If there is no property with the specified name, if the 1027 * specified name is empty or {@code null}, or if the property 1028 * does not have the correct numeric format, then {@code null} is 1029 * returned. 1030 * 1031 * <p>In other words, this method returns an {@code Integer} 1032 * object equal to the value of: 1033 * 1034 * <blockquote> 1035 * {@code getInteger(nm, null)} 1036 * </blockquote> 1037 * 1038 * @param nm property name. 1039 * @return the {@code Integer} value of the property. 1040 * @throws SecurityException for the same reasons as 1041 * {@link System#getProperty(String) System.getProperty} 1042 * @see java.lang.System#getProperty(java.lang.String) 1043 * @see java.lang.System#getProperty(java.lang.String, java.lang.String) 1044 */ 1045 public static Integer getInteger(String nm) { 1046 return getInteger(nm, null); 1047 } 1048 1049 /** 1050 * Determines the integer value of the system property with the 1051 * specified name. 1052 * 1053 * <p>The first argument is treated as the name of a system 1054 * property. System properties are accessible through the {@link 1055 * java.lang.System#getProperty(java.lang.String)} method. The 1056 * string value of this property is then interpreted as an integer 1057 * value using the grammar supported by {@link Integer#decode decode} and 1058 * an {@code Integer} object representing this value is returned. 1059 * 1060 * <p>The second argument is the default value. An {@code Integer} object 1061 * that represents the value of the second argument is returned if there 1062 * is no property of the specified name, if the property does not have 1063 * the correct numeric format, or if the specified name is empty or 1064 * {@code null}. 1065 * 1066 * <p>In other words, this method returns an {@code Integer} object 1067 * equal to the value of: 1068 * 1069 * <blockquote> 1070 * {@code getInteger(nm, new Integer(val))} 1071 * </blockquote> 1072 * 1073 * but in practice it may be implemented in a manner such as: 1074 * 1075 * <blockquote><pre> 1076 * Integer result = getInteger(nm, null); 1077 * return (result == null) ? new Integer(val) : result; 1078 * </pre></blockquote> 1079 * 1080 * to avoid the unnecessary allocation of an {@code Integer} 1081 * object when the default value is not needed. 1082 * 1083 * @param nm property name. 1084 * @param val default value. 1085 * @return the {@code Integer} value of the property. 1086 * @throws SecurityException for the same reasons as 1087 * {@link System#getProperty(String) System.getProperty} 1088 * @see java.lang.System#getProperty(java.lang.String) 1089 * @see java.lang.System#getProperty(java.lang.String, java.lang.String) 1090 */ 1091 public static Integer getInteger(String nm, int val) { 1092 Integer result = getInteger(nm, null); 1093 return (result == null) ? Integer.valueOf(val) : result; 1094 } 1095 1096 /** 1097 * Returns the integer value of the system property with the 1098 * specified name. The first argument is treated as the name of a 1099 * system property. System properties are accessible through the 1100 * {@link java.lang.System#getProperty(java.lang.String)} method. 1101 * The string value of this property is then interpreted as an 1102 * integer value, as per the {@link Integer#decode decode} method, 1103 * and an {@code Integer} object representing this value is 1104 * returned; in summary: 1105 * 1106 * <ul><li>If the property value begins with the two ASCII characters 1107 * {@code 0x} or the ASCII character {@code #}, not 1108 * followed by a minus sign, then the rest of it is parsed as a 1109 * hexadecimal integer exactly as by the method 1110 * {@link #valueOf(java.lang.String, int)} with radix 16. 1111 * <li>If the property value begins with the ASCII character 1112 * {@code 0} followed by another character, it is parsed as an 1113 * octal integer exactly as by the method 1114 * {@link #valueOf(java.lang.String, int)} with radix 8. 1115 * <li>Otherwise, the property value is parsed as a decimal integer 1116 * exactly as by the method {@link #valueOf(java.lang.String, int)} 1117 * with radix 10. 1118 * </ul> 1119 * 1120 * <p>The second argument is the default value. The default value is 1121 * returned if there is no property of the specified name, if the 1122 * property does not have the correct numeric format, or if the 1123 * specified name is empty or {@code null}. 1124 * 1125 * @param nm property name. 1126 * @param val default value. 1127 * @return the {@code Integer} value of the property. 1128 * @throws SecurityException for the same reasons as 1129 * {@link System#getProperty(String) System.getProperty} 1130 * @see System#getProperty(java.lang.String) 1131 * @see System#getProperty(java.lang.String, java.lang.String) 1132 */ 1133 public static Integer getInteger(String nm, Integer val) { 1134 String v = null; 1135 try { 1136 v = System.getProperty(nm); 1137 } catch (IllegalArgumentException | NullPointerException e) { 1138 } 1139 if (v != null) { 1140 try { 1141 return Integer.decode(v); 1142 } catch (NumberFormatException e) { 1143 } 1144 } 1145 return val; 1146 } 1147 1148 /** 1149 * Decodes a {@code String} into an {@code Integer}. 1150 * Accepts decimal, hexadecimal, and octal numbers given 1151 * by the following grammar: 1152 * 1153 * <blockquote> 1154 * <dl> 1155 * <dt><i>DecodableString:</i> 1156 * <dd><i>Sign<sub>opt</sub> DecimalNumeral</i> 1157 * <dd><i>Sign<sub>opt</sub></i> {@code 0x} <i>HexDigits</i> 1158 * <dd><i>Sign<sub>opt</sub></i> {@code 0X} <i>HexDigits</i> 1159 * <dd><i>Sign<sub>opt</sub></i> {@code #} <i>HexDigits</i> 1160 * <dd><i>Sign<sub>opt</sub></i> {@code 0} <i>OctalDigits</i> 1161 * 1162 * <dt><i>Sign:</i> 1163 * <dd>{@code -} 1164 * <dd>{@code +} 1165 * </dl> 1166 * </blockquote> 1167 * 1168 * <i>DecimalNumeral</i>, <i>HexDigits</i>, and <i>OctalDigits</i> 1169 * are as defined in section 3.10.1 of 1170 * <cite>The Java™ Language Specification</cite>, 1171 * except that underscores are not accepted between digits. 1172 * 1173 * <p>The sequence of characters following an optional 1174 * sign and/or radix specifier ("{@code 0x}", "{@code 0X}", 1175 * "{@code #}", or leading zero) is parsed as by the {@code 1176 * Integer.parseInt} method with the indicated radix (10, 16, or 1177 * 8). This sequence of characters must represent a positive 1178 * value or a {@link NumberFormatException} will be thrown. The 1179 * result is negated if first character of the specified {@code 1180 * String} is the minus sign. No whitespace characters are 1181 * permitted in the {@code String}. 1182 * 1183 * @param nm the {@code String} to decode. 1184 * @return an {@code Integer} object holding the {@code int} 1185 * value represented by {@code nm} 1186 * @exception NumberFormatException if the {@code String} does not 1187 * contain a parsable integer. 1188 * @see java.lang.Integer#parseInt(java.lang.String, int) 1189 */ 1190 public static Integer decode(String nm) throws NumberFormatException { 1191 int radix = 10; 1192 int index = 0; 1193 boolean negative = false; 1194 Integer result; 1195 1196 if (nm.length() == 0) 1197 throw new NumberFormatException("Zero length string"); 1198 char firstChar = nm.charAt(0); 1199 // Handle sign, if present 1200 if (firstChar == '-') { 1201 negative = true; 1202 index++; 1203 } else if (firstChar == '+') 1204 index++; 1205 1206 // Handle radix specifier, if present 1207 if (nm.startsWith("0x", index) || nm.startsWith("0X", index)) { 1208 index += 2; 1209 radix = 16; 1210 } 1211 else if (nm.startsWith("#", index)) { 1212 index ++; 1213 radix = 16; 1214 } 1215 else if (nm.startsWith("0", index) && nm.length() > 1 + index) { 1216 index ++; 1217 radix = 8; 1218 } 1219 1220 if (nm.startsWith("-", index) || nm.startsWith("+", index)) 1221 throw new NumberFormatException("Sign character in wrong position"); 1222 1223 try { 1224 result = Integer.valueOf(nm.substring(index), radix); 1225 result = negative ? Integer.valueOf(-result.intValue()) : result; 1226 } catch (NumberFormatException e) { 1227 // If number is Integer.MIN_VALUE, we'll end up here. The next line 1228 // handles this case, and causes any genuine format error to be 1229 // rethrown. 1230 String constant = negative ? ("-" + nm.substring(index)) 1231 : nm.substring(index); 1232 result = Integer.valueOf(constant, radix); 1233 } 1234 return result; 1235 } 1236 1237 /** 1238 * Compares two {@code Integer} objects numerically. 1239 * 1240 * @param anotherInteger the {@code Integer} to be compared. 1241 * @return the value {@code 0} if this {@code Integer} is 1242 * equal to the argument {@code Integer}; a value less than 1243 * {@code 0} if this {@code Integer} is numerically less 1244 * than the argument {@code Integer}; and a value greater 1245 * than {@code 0} if this {@code Integer} is numerically 1246 * greater than the argument {@code Integer} (signed 1247 * comparison). 1248 * @since 1.2 1249 */ 1250 public int compareTo(Integer anotherInteger) { 1251 return compare(this.value, anotherInteger.value); 1252 } 1253 1254 /** 1255 * Compares two {@code int} values numerically. 1256 * The value returned is identical to what would be returned by: 1257 * <pre> 1258 * Integer.valueOf(x).compareTo(Integer.valueOf(y)) 1259 * </pre> 1260 * 1261 * @param x the first {@code int} to compare 1262 * @param y the second {@code int} to compare 1263 * @return the value {@code 0} if {@code x == y}; 1264 * a value less than {@code 0} if {@code x < y}; and 1265 * a value greater than {@code 0} if {@code x > y} 1266 * @since 1.7 1267 */ 1268 public static int compare(int x, int y) { 1269 return (x < y) ? -1 : ((x == y) ? 0 : 1); 1270 } 1271 1272 /** 1273 * Compares two {@code int} values numerically treating the values 1274 * as unsigned. 1275 * 1276 * @param x the first {@code int} to compare 1277 * @param y the second {@code int} to compare 1278 * @return the value {@code 0} if {@code x == y}; a value less 1279 * than {@code 0} if {@code x < y} as unsigned values; and 1280 * a value greater than {@code 0} if {@code x > y} as 1281 * unsigned values 1282 * @since 1.8 1283 */ 1284 public static int compareUnsigned(int x, int y) { 1285 return compare(x + MIN_VALUE, y + MIN_VALUE); 1286 } 1287 1288 /** 1289 * Converts the argument to a {@code long} by an unsigned 1290 * conversion. In an unsigned conversion to a {@code long}, the 1291 * high-order 32 bits of the {@code long} are zero and the 1292 * low-order 32 bits are equal to the bits of the integer 1293 * argument. 1294 * 1295 * Consequently, zero and positive {@code int} values are mapped 1296 * to a numerically equal {@code long} value and negative {@code 1297 * int} values are mapped to a {@code long} value equal to the 1298 * input plus 2<sup>32</sup>. 1299 * 1300 * @param x the value to convert to an unsigned {@code long} 1301 * @return the argument converted to {@code long} by an unsigned 1302 * conversion 1303 * @since 1.8 1304 */ 1305 public static long toUnsignedLong(int x) { 1306 return ((long) x) & 0xffffffffL; 1307 } 1308 1309 /** 1310 * Returns the unsigned quotient of dividing the first argument by 1311 * the second where each argument and the result is interpreted as 1312 * an unsigned value. 1313 * 1314 * <p>Note that in two's complement arithmetic, the three other 1315 * basic arithmetic operations of add, subtract, and multiply are 1316 * bit-wise identical if the two operands are regarded as both 1317 * being signed or both being unsigned. Therefore separate {@code 1318 * addUnsigned}, etc. methods are not provided. 1319 * 1320 * @param dividend the value to be divided 1321 * @param divisor the value doing the dividing 1322 * @return the unsigned quotient of the first argument divided by 1323 * the second argument 1324 * @see #remainderUnsigned 1325 * @since 1.8 1326 */ 1327 public static int divideUnsigned(int dividend, int divisor) { 1328 // In lieu of tricky code, for now just use long arithmetic. 1329 return (int)(toUnsignedLong(dividend) / toUnsignedLong(divisor)); 1330 } 1331 1332 /** 1333 * Returns the unsigned remainder from dividing the first argument 1334 * by the second where each argument and the result is interpreted 1335 * as an unsigned value. 1336 * 1337 * @param dividend the value to be divided 1338 * @param divisor the value doing the dividing 1339 * @return the unsigned remainder of the first argument divided by 1340 * the second argument 1341 * @see #divideUnsigned 1342 * @since 1.8 1343 */ 1344 public static int remainderUnsigned(int dividend, int divisor) { 1345 // In lieu of tricky code, for now just use long arithmetic. 1346 return (int)(toUnsignedLong(dividend) % toUnsignedLong(divisor)); 1347 } 1348 1349 1350 // Bit twiddling 1351 1352 /** 1353 * The number of bits used to represent an {@code int} value in two's 1354 * complement binary form. 1355 * 1356 * @since 1.5 1357 */ 1358 @Native public static final int SIZE = 32; 1359 1360 /** 1361 * The number of bytes used to represent a {@code int} value in two's 1362 * complement binary form. 1363 * 1364 * @since 1.8 1365 */ 1366 public static final int BYTES = SIZE / Byte.SIZE; 1367 1368 /** 1369 * Returns an {@code int} value with at most a single one-bit, in the 1370 * position of the highest-order ("leftmost") one-bit in the specified 1371 * {@code int} value. Returns zero if the specified value has no 1372 * one-bits in its two's complement binary representation, that is, if it 1373 * is equal to zero. 1374 * 1375 * @param i the value whose highest one bit is to be computed 1376 * @return an {@code int} value with a single one-bit, in the position 1377 * of the highest-order one-bit in the specified value, or zero if 1378 * the specified value is itself equal to zero. 1379 * @since 1.5 1380 */ 1381 public static int highestOneBit(int i) { 1382 // HD, Figure 3-1 1383 i |= (i >> 1); 1384 i |= (i >> 2); 1385 i |= (i >> 4); 1386 i |= (i >> 8); 1387 i |= (i >> 16); 1388 return i - (i >>> 1); 1389 } 1390 1391 /** 1392 * Returns an {@code int} value with at most a single one-bit, in the 1393 * position of the lowest-order ("rightmost") one-bit in the specified 1394 * {@code int} value. Returns zero if the specified value has no 1395 * one-bits in its two's complement binary representation, that is, if it 1396 * is equal to zero. 1397 * 1398 * @param i the value whose lowest one bit is to be computed 1399 * @return an {@code int} value with a single one-bit, in the position 1400 * of the lowest-order one-bit in the specified value, or zero if 1401 * the specified value is itself equal to zero. 1402 * @since 1.5 1403 */ 1404 public static int lowestOneBit(int i) { 1405 // HD, Section 2-1 1406 return i & -i; 1407 } 1408 1409 /** 1410 * Returns the number of zero bits preceding the highest-order 1411 * ("leftmost") one-bit in the two's complement binary representation 1412 * of the specified {@code int} value. Returns 32 if the 1413 * specified value has no one-bits in its two's complement representation, 1414 * in other words if it is equal to zero. 1415 * 1416 * <p>Note that this method is closely related to the logarithm base 2. 1417 * For all positive {@code int} values x: 1418 * <ul> 1419 * <li>floor(log<sub>2</sub>(x)) = {@code 31 - numberOfLeadingZeros(x)} 1420 * <li>ceil(log<sub>2</sub>(x)) = {@code 32 - numberOfLeadingZeros(x - 1)} 1421 * </ul> 1422 * 1423 * @param i the value whose number of leading zeros is to be computed 1424 * @return the number of zero bits preceding the highest-order 1425 * ("leftmost") one-bit in the two's complement binary representation 1426 * of the specified {@code int} value, or 32 if the value 1427 * is equal to zero. 1428 * @since 1.5 1429 */ 1430 public static int numberOfLeadingZeros(int i) { 1431 // HD, Figure 5-6 1432 if (i == 0) 1433 return 32; 1434 int n = 1; 1435 if (i >>> 16 == 0) { n += 16; i <<= 16; } 1436 if (i >>> 24 == 0) { n += 8; i <<= 8; } 1437 if (i >>> 28 == 0) { n += 4; i <<= 4; } 1438 if (i >>> 30 == 0) { n += 2; i <<= 2; } 1439 n -= i >>> 31; 1440 return n; 1441 } 1442 1443 /** 1444 * Returns the number of zero bits following the lowest-order ("rightmost") 1445 * one-bit in the two's complement binary representation of the specified 1446 * {@code int} value. Returns 32 if the specified value has no 1447 * one-bits in its two's complement representation, in other words if it is 1448 * equal to zero. 1449 * 1450 * @param i the value whose number of trailing zeros is to be computed 1451 * @return the number of zero bits following the lowest-order ("rightmost") 1452 * one-bit in the two's complement binary representation of the 1453 * specified {@code int} value, or 32 if the value is equal 1454 * to zero. 1455 * @since 1.5 1456 */ numberOfTrailingZeros(int i)1457 public static int numberOfTrailingZeros(int i) { 1458 // HD, Figure 5-14 1459 int y; 1460 if (i == 0) return 32; 1461 int n = 31; 1462 y = i <<16; if (y != 0) { n = n -16; i = y; } 1463 y = i << 8; if (y != 0) { n = n - 8; i = y; } 1464 y = i << 4; if (y != 0) { n = n - 4; i = y; } 1465 y = i << 2; if (y != 0) { n = n - 2; i = y; } 1466 return n - ((i << 1) >>> 31); 1467 } 1468 1469 /** 1470 * Returns the number of one-bits in the two's complement binary 1471 * representation of the specified {@code int} value. This function is 1472 * sometimes referred to as the <i>population count</i>. 1473 * 1474 * @param i the value whose bits are to be counted 1475 * @return the number of one-bits in the two's complement binary 1476 * representation of the specified {@code int} value. 1477 * @since 1.5 1478 */ bitCount(int i)1479 public static int bitCount(int i) { 1480 // HD, Figure 5-2 1481 i = i - ((i >>> 1) & 0x55555555); 1482 i = (i & 0x33333333) + ((i >>> 2) & 0x33333333); 1483 i = (i + (i >>> 4)) & 0x0f0f0f0f; 1484 i = i + (i >>> 8); 1485 i = i + (i >>> 16); 1486 return i & 0x3f; 1487 } 1488 1489 /** 1490 * Returns the value obtained by rotating the two's complement binary 1491 * representation of the specified {@code int} value left by the 1492 * specified number of bits. (Bits shifted out of the left hand, or 1493 * high-order, side reenter on the right, or low-order.) 1494 * 1495 * <p>Note that left rotation with a negative distance is equivalent to 1496 * right rotation: {@code rotateLeft(val, -distance) == rotateRight(val, 1497 * distance)}. Note also that rotation by any multiple of 32 is a 1498 * no-op, so all but the last five bits of the rotation distance can be 1499 * ignored, even if the distance is negative: {@code rotateLeft(val, 1500 * distance) == rotateLeft(val, distance & 0x1F)}. 1501 * 1502 * @param i the value whose bits are to be rotated left 1503 * @param distance the number of bit positions to rotate left 1504 * @return the value obtained by rotating the two's complement binary 1505 * representation of the specified {@code int} value left by the 1506 * specified number of bits. 1507 * @since 1.5 1508 */ rotateLeft(int i, int distance)1509 public static int rotateLeft(int i, int distance) { 1510 return (i << distance) | (i >>> -distance); 1511 } 1512 1513 /** 1514 * Returns the value obtained by rotating the two's complement binary 1515 * representation of the specified {@code int} value right by the 1516 * specified number of bits. (Bits shifted out of the right hand, or 1517 * low-order, side reenter on the left, or high-order.) 1518 * 1519 * <p>Note that right rotation with a negative distance is equivalent to 1520 * left rotation: {@code rotateRight(val, -distance) == rotateLeft(val, 1521 * distance)}. Note also that rotation by any multiple of 32 is a 1522 * no-op, so all but the last five bits of the rotation distance can be 1523 * ignored, even if the distance is negative: {@code rotateRight(val, 1524 * distance) == rotateRight(val, distance & 0x1F)}. 1525 * 1526 * @param i the value whose bits are to be rotated right 1527 * @param distance the number of bit positions to rotate right 1528 * @return the value obtained by rotating the two's complement binary 1529 * representation of the specified {@code int} value right by the 1530 * specified number of bits. 1531 * @since 1.5 1532 */ rotateRight(int i, int distance)1533 public static int rotateRight(int i, int distance) { 1534 return (i >>> distance) | (i << -distance); 1535 } 1536 1537 /** 1538 * Returns the value obtained by reversing the order of the bits in the 1539 * two's complement binary representation of the specified {@code int} 1540 * value. 1541 * 1542 * @param i the value to be reversed 1543 * @return the value obtained by reversing order of the bits in the 1544 * specified {@code int} value. 1545 * @since 1.5 1546 */ reverse(int i)1547 public static int reverse(int i) { 1548 // HD, Figure 7-1 1549 i = (i & 0x55555555) << 1 | (i >>> 1) & 0x55555555; 1550 i = (i & 0x33333333) << 2 | (i >>> 2) & 0x33333333; 1551 i = (i & 0x0f0f0f0f) << 4 | (i >>> 4) & 0x0f0f0f0f; 1552 i = (i << 24) | ((i & 0xff00) << 8) | 1553 ((i >>> 8) & 0xff00) | (i >>> 24); 1554 return i; 1555 } 1556 1557 /** 1558 * Returns the signum function of the specified {@code int} value. (The 1559 * return value is -1 if the specified value is negative; 0 if the 1560 * specified value is zero; and 1 if the specified value is positive.) 1561 * 1562 * @param i the value whose signum is to be computed 1563 * @return the signum function of the specified {@code int} value. 1564 * @since 1.5 1565 */ signum(int i)1566 public static int signum(int i) { 1567 // HD, Section 2-7 1568 return (i >> 31) | (-i >>> 31); 1569 } 1570 1571 /** 1572 * Returns the value obtained by reversing the order of the bytes in the 1573 * two's complement representation of the specified {@code int} value. 1574 * 1575 * @param i the value whose bytes are to be reversed 1576 * @return the value obtained by reversing the bytes in the specified 1577 * {@code int} value. 1578 * @since 1.5 1579 */ reverseBytes(int i)1580 public static int reverseBytes(int i) { 1581 return ((i >>> 24) ) | 1582 ((i >> 8) & 0xFF00) | 1583 ((i << 8) & 0xFF0000) | 1584 ((i << 24)); 1585 } 1586 1587 /** 1588 * Adds two integers together as per the + operator. 1589 * 1590 * @param a the first operand 1591 * @param b the second operand 1592 * @return the sum of {@code a} and {@code b} 1593 * @see java.util.function.BinaryOperator 1594 * @since 1.8 1595 */ sum(int a, int b)1596 public static int sum(int a, int b) { 1597 return a + b; 1598 } 1599 1600 /** 1601 * Returns the greater of two {@code int} values 1602 * as if by calling {@link Math#max(int, int) Math.max}. 1603 * 1604 * @param a the first operand 1605 * @param b the second operand 1606 * @return the greater of {@code a} and {@code b} 1607 * @see java.util.function.BinaryOperator 1608 * @since 1.8 1609 */ max(int a, int b)1610 public static int max(int a, int b) { 1611 return Math.max(a, b); 1612 } 1613 1614 /** 1615 * Returns the smaller of two {@code int} values 1616 * as if by calling {@link Math#min(int, int) Math.min}. 1617 * 1618 * @param a the first operand 1619 * @param b the second operand 1620 * @return the smaller of {@code a} and {@code b} 1621 * @see java.util.function.BinaryOperator 1622 * @since 1.8 1623 */ min(int a, int b)1624 public static int min(int a, int b) { 1625 return Math.min(a, b); 1626 } 1627 1628 /** use serialVersionUID from JDK 1.0.2 for interoperability */ 1629 @Native private static final long serialVersionUID = 1360826667806852920L; 1630 } 1631