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>) int[].class.getComponentType(); 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 // Use special constructor which takes over "buf". 319 return new String(buf); 320 } 321 322 /** 323 * Format a long (treated as unsigned) into a character buffer. 324 * @param val the unsigned int to format 325 * @param shift the log2 of the base to format in (4 for hex, 3 for octal, 1 for binary) 326 * @param buf the character buffer to write to 327 * @param offset the offset in the destination buffer to start at 328 * @param len the number of characters to write 329 * @return the lowest character location used 330 */ formatUnsignedInt(int val, int shift, char[] buf, int offset, int len)331 static int formatUnsignedInt(int val, int shift, char[] buf, int offset, int len) { 332 int charPos = len; 333 int radix = 1 << shift; 334 int mask = radix - 1; 335 do { 336 buf[offset + --charPos] = Integer.digits[val & mask]; 337 val >>>= shift; 338 } while (val != 0 && charPos > 0); 339 340 return charPos; 341 } 342 343 private static final String[] SMALL_NEG_VALUES = new String[100]; 344 private static final String[] SMALL_NONNEG_VALUES = new String[100]; 345 346 final static char [] DigitTens = { 347 '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', 348 '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', 349 '2', '2', '2', '2', '2', '2', '2', '2', '2', '2', 350 '3', '3', '3', '3', '3', '3', '3', '3', '3', '3', 351 '4', '4', '4', '4', '4', '4', '4', '4', '4', '4', 352 '5', '5', '5', '5', '5', '5', '5', '5', '5', '5', 353 '6', '6', '6', '6', '6', '6', '6', '6', '6', '6', 354 '7', '7', '7', '7', '7', '7', '7', '7', '7', '7', 355 '8', '8', '8', '8', '8', '8', '8', '8', '8', '8', 356 '9', '9', '9', '9', '9', '9', '9', '9', '9', '9', 357 } ; 358 359 final static char [] DigitOnes = { 360 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 361 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 362 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 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 } ; 371 372 // I use the "invariant division by multiplication" trick to 373 // accelerate Integer.toString. In particular we want to 374 // avoid division by 10. 375 // 376 // The "trick" has roughly the same performance characteristics 377 // as the "classic" Integer.toString code on a non-JIT VM. 378 // The trick avoids .rem and .div calls but has a longer code 379 // path and is thus dominated by dispatch overhead. In the 380 // JIT case the dispatch overhead doesn't exist and the 381 // "trick" is considerably faster than the classic code. 382 // 383 // TODO-FIXME: convert (x * 52429) into the equiv shift-add 384 // sequence. 385 // 386 // RE: Division by Invariant Integers using Multiplication 387 // T Gralund, P Montgomery 388 // ACM PLDI 1994 389 // 390 391 /** 392 * Returns a {@code String} object representing the 393 * specified integer. The argument is converted to signed decimal 394 * representation and returned as a string, exactly as if the 395 * argument and radix 10 were given as arguments to the {@link 396 * #toString(int, int)} method. 397 * 398 * @param i an integer to be converted. 399 * @return a string representation of the argument in base 10. 400 */ toString(int i)401 public static String toString(int i) { 402 if (i == Integer.MIN_VALUE) 403 return "-2147483648"; 404 405 // Android-changed: cache the string literal for small values. 406 boolean negative = i < 0; 407 boolean small = negative ? i > -100 : i < 100; 408 if (small) { 409 final String[] smallValues = negative ? SMALL_NEG_VALUES : SMALL_NONNEG_VALUES; 410 411 if (negative) { 412 i = -i; 413 if (smallValues[i] == null) { 414 smallValues[i] = 415 i < 10 ? new String(new char[]{'-', DigitOnes[i]}) 416 : new String(new char[]{'-', DigitTens[i], DigitOnes[i]}); 417 } 418 } else { 419 if (smallValues[i] == null) { 420 smallValues[i] = 421 i < 10 ? new String(new char[]{DigitOnes[i]}) 422 : new String(new char[]{DigitTens[i], DigitOnes[i]}); 423 } 424 } 425 return smallValues[i]; 426 } 427 428 int size = negative ? stringSize(-i) + 1 : stringSize(i); 429 char[] buf = new char[size]; 430 getChars(i, size, buf); 431 return new String(buf); 432 } 433 434 /** 435 * Returns a string representation of the argument as an unsigned 436 * decimal value. 437 * 438 * The argument is converted to unsigned decimal representation 439 * and returned as a string exactly as if the argument and radix 440 * 10 were given as arguments to the {@link #toUnsignedString(int, 441 * int)} method. 442 * 443 * @param i an integer to be converted to an unsigned string. 444 * @return an unsigned string representation of the argument. 445 * @see #toUnsignedString(int, int) 446 * @since 1.8 447 */ 448 public static String toUnsignedString(int i) { 449 return Long.toString(toUnsignedLong(i)); 450 } 451 452 /** 453 * Places characters representing the integer i into the 454 * character array buf. The characters are placed into 455 * the buffer backwards starting with the least significant 456 * digit at the specified index (exclusive), and working 457 * backwards from there. 458 * 459 * Will fail if i == Integer.MIN_VALUE 460 */ 461 static void getChars(int i, int index, char[] buf) { 462 int q, r; 463 int charPos = index; 464 char sign = 0; 465 466 if (i < 0) { 467 sign = '-'; 468 i = -i; 469 } 470 471 // Generate two digits per iteration 472 while (i >= 65536) { 473 q = i / 100; 474 // really: r = i - (q * 100); 475 r = i - ((q << 6) + (q << 5) + (q << 2)); 476 i = q; 477 buf [--charPos] = DigitOnes[r]; 478 buf [--charPos] = DigitTens[r]; 479 } 480 481 // Fall thru to fast mode for smaller numbers 482 // assert(i <= 65536, i); 483 for (;;) { 484 q = (i * 52429) >>> (16+3); 485 r = i - ((q << 3) + (q << 1)); // r = i-(q*10) ... 486 buf [--charPos] = digits [r]; 487 i = q; 488 if (i == 0) break; 489 } 490 if (sign != 0) { 491 buf [--charPos] = sign; 492 } 493 } 494 495 final static int [] sizeTable = { 9, 99, 999, 9999, 99999, 999999, 9999999, 496 99999999, 999999999, Integer.MAX_VALUE }; 497 498 // Requires positive x 499 static int stringSize(int x) { 500 for (int i=0; ; i++) 501 if (x <= sizeTable[i]) 502 return i+1; 503 } 504 505 /** 506 * Parses the string argument as a signed integer in the radix 507 * specified by the second argument. The characters in the string 508 * must all be digits of the specified radix (as determined by 509 * whether {@link java.lang.Character#digit(char, int)} returns a 510 * nonnegative value), except that the first character may be an 511 * ASCII minus sign {@code '-'} ({@code '\u005Cu002D'}) to 512 * indicate a negative value or an ASCII plus sign {@code '+'} 513 * ({@code '\u005Cu002B'}) to indicate a positive value. The 514 * resulting integer value is returned. 515 * 516 * <p>An exception of type {@code NumberFormatException} is 517 * thrown if any of the following situations occurs: 518 * <ul> 519 * <li>The first argument is {@code null} or is a string of 520 * length zero. 521 * 522 * <li>The radix is either smaller than 523 * {@link java.lang.Character#MIN_RADIX} or 524 * larger than {@link java.lang.Character#MAX_RADIX}. 525 * 526 * <li>Any character of the string is not a digit of the specified 527 * radix, except that the first character may be a minus sign 528 * {@code '-'} ({@code '\u005Cu002D'}) or plus sign 529 * {@code '+'} ({@code '\u005Cu002B'}) provided that the 530 * string is longer than length 1. 531 * 532 * <li>The value represented by the string is not a value of type 533 * {@code int}. 534 * </ul> 535 * 536 * <p>Examples: 537 * <blockquote><pre> 538 * parseInt("0", 10) returns 0 539 * parseInt("473", 10) returns 473 540 * parseInt("+42", 10) returns 42 541 * parseInt("-0", 10) returns 0 542 * parseInt("-FF", 16) returns -255 543 * parseInt("1100110", 2) returns 102 544 * parseInt("2147483647", 10) returns 2147483647 545 * parseInt("-2147483648", 10) returns -2147483648 546 * parseInt("2147483648", 10) throws a NumberFormatException 547 * parseInt("99", 8) throws a NumberFormatException 548 * parseInt("Kona", 10) throws a NumberFormatException 549 * parseInt("Kona", 27) returns 411787 550 * </pre></blockquote> 551 * 552 * @param s the {@code String} containing the integer 553 * representation to be parsed 554 * @param radix the radix to be used while parsing {@code s}. 555 * @return the integer represented by the string argument in the 556 * specified radix. 557 * @exception NumberFormatException if the {@code String} 558 * does not contain a parsable {@code int}. 559 */ 560 public static int parseInt(String s, int radix) 561 throws NumberFormatException 562 { 563 /* 564 * WARNING: This method may be invoked early during VM initialization 565 * before IntegerCache is initialized. Care must be taken to not use 566 * the valueOf method. 567 */ 568 569 if (s == null) { 570 throw new NumberFormatException("s == null"); 571 } 572 573 if (radix < Character.MIN_RADIX) { 574 throw new NumberFormatException("radix " + radix + 575 " less than Character.MIN_RADIX"); 576 } 577 578 if (radix > Character.MAX_RADIX) { 579 throw new NumberFormatException("radix " + radix + 580 " greater than Character.MAX_RADIX"); 581 } 582 583 int result = 0; 584 boolean negative = false; 585 int i = 0, len = s.length(); 586 int limit = -Integer.MAX_VALUE; 587 int multmin; 588 int digit; 589 590 if (len > 0) { 591 char firstChar = s.charAt(0); 592 if (firstChar < '0') { // Possible leading "+" or "-" 593 if (firstChar == '-') { 594 negative = true; 595 limit = Integer.MIN_VALUE; 596 } else if (firstChar != '+') 597 throw NumberFormatException.forInputString(s); 598 599 if (len == 1) // Cannot have lone "+" or "-" 600 throw NumberFormatException.forInputString(s); 601 i++; 602 } 603 multmin = limit / radix; 604 while (i < len) { 605 // Accumulating negatively avoids surprises near MAX_VALUE 606 digit = Character.digit(s.charAt(i++),radix); 607 if (digit < 0) { 608 throw NumberFormatException.forInputString(s); 609 } 610 if (result < multmin) { 611 throw NumberFormatException.forInputString(s); 612 } 613 result *= radix; 614 if (result < limit + digit) { 615 throw NumberFormatException.forInputString(s); 616 } 617 result -= digit; 618 } 619 } else { 620 throw NumberFormatException.forInputString(s); 621 } 622 return negative ? result : -result; 623 } 624 625 /** 626 * Parses the string argument as a signed decimal integer. The 627 * characters in the string must all be decimal digits, except 628 * that the first character may be an ASCII minus sign {@code '-'} 629 * ({@code '\u005Cu002D'}) to indicate a negative value or an 630 * ASCII plus sign {@code '+'} ({@code '\u005Cu002B'}) to 631 * indicate a positive value. The resulting integer value is 632 * returned, exactly as if the argument and the radix 10 were 633 * given as arguments to the {@link #parseInt(java.lang.String, 634 * int)} method. 635 * 636 * @param s a {@code String} containing the {@code int} 637 * representation to be parsed 638 * @return the integer value represented by the argument in decimal. 639 * @exception NumberFormatException if the string does not contain a 640 * parsable integer. 641 */ 642 public static int parseInt(String s) throws NumberFormatException { 643 return parseInt(s,10); 644 } 645 646 /** 647 * Parses the string argument as an unsigned integer in the radix 648 * specified by the second argument. An unsigned integer maps the 649 * values usually associated with negative numbers to positive 650 * numbers larger than {@code MAX_VALUE}. 651 * 652 * The characters in the string must all be digits of the 653 * specified radix (as determined by whether {@link 654 * java.lang.Character#digit(char, int)} returns a nonnegative 655 * value), except that the first character may be an ASCII plus 656 * sign {@code '+'} ({@code '\u005Cu002B'}). The resulting 657 * integer value is returned. 658 * 659 * <p>An exception of type {@code NumberFormatException} is 660 * thrown if any of the following situations occurs: 661 * <ul> 662 * <li>The first argument is {@code null} or is a string of 663 * length zero. 664 * 665 * <li>The radix is either smaller than 666 * {@link java.lang.Character#MIN_RADIX} or 667 * larger than {@link java.lang.Character#MAX_RADIX}. 668 * 669 * <li>Any character of the string is not a digit of the specified 670 * radix, except that the first character may be a plus sign 671 * {@code '+'} ({@code '\u005Cu002B'}) provided that the 672 * string is longer than length 1. 673 * 674 * <li>The value represented by the string is larger than the 675 * largest unsigned {@code int}, 2<sup>32</sup>-1. 676 * 677 * </ul> 678 * 679 * 680 * @param s the {@code String} containing the unsigned integer 681 * representation to be parsed 682 * @param radix the radix to be used while parsing {@code s}. 683 * @return the integer represented by the string argument in the 684 * specified radix. 685 * @throws NumberFormatException if the {@code String} 686 * does not contain a parsable {@code int}. 687 * @since 1.8 688 */ 689 public static int parseUnsignedInt(String s, int radix) 690 throws NumberFormatException { 691 if (s == null) { 692 throw new NumberFormatException("null"); 693 } 694 695 int len = s.length(); 696 if (len > 0) { 697 char firstChar = s.charAt(0); 698 if (firstChar == '-') { 699 throw new 700 NumberFormatException(String.format("Illegal leading minus sign " + 701 "on unsigned string %s.", s)); 702 } else { 703 if (len <= 5 || // Integer.MAX_VALUE in Character.MAX_RADIX is 6 digits 704 (radix == 10 && len <= 9) ) { // Integer.MAX_VALUE in base 10 is 10 digits 705 return parseInt(s, radix); 706 } else { 707 long ell = Long.parseLong(s, radix); 708 if ((ell & 0xffff_ffff_0000_0000L) == 0) { 709 return (int) ell; 710 } else { 711 throw new 712 NumberFormatException(String.format("String value %s exceeds " + 713 "range of unsigned int.", s)); 714 } 715 } 716 } 717 } else { 718 throw NumberFormatException.forInputString(s); 719 } 720 } 721 722 /** 723 * Parses the string argument as an unsigned decimal integer. The 724 * characters in the string must all be decimal digits, except 725 * that the first character may be an an ASCII plus sign {@code 726 * '+'} ({@code '\u005Cu002B'}). The resulting integer value 727 * is returned, exactly as if the argument and the radix 10 were 728 * given as arguments to the {@link 729 * #parseUnsignedInt(java.lang.String, int)} method. 730 * 731 * @param s a {@code String} containing the unsigned {@code int} 732 * representation to be parsed 733 * @return the unsigned integer value represented by the argument in decimal. 734 * @throws NumberFormatException if the string does not contain a 735 * parsable unsigned integer. 736 * @since 1.8 737 */ 738 public static int parseUnsignedInt(String s) throws NumberFormatException { 739 return parseUnsignedInt(s, 10); 740 } 741 742 /** 743 * Returns an {@code Integer} object holding the value 744 * extracted from the specified {@code String} when parsed 745 * with the radix given by the second argument. The first argument 746 * is interpreted as representing a signed integer in the radix 747 * specified by the second argument, exactly as if the arguments 748 * were given to the {@link #parseInt(java.lang.String, int)} 749 * method. The result is an {@code Integer} object that 750 * represents the integer value specified by the string. 751 * 752 * <p>In other words, this method returns an {@code Integer} 753 * object equal to the value of: 754 * 755 * <blockquote> 756 * {@code new Integer(Integer.parseInt(s, radix))} 757 * </blockquote> 758 * 759 * @param s the string to be parsed. 760 * @param radix the radix to be used in interpreting {@code s} 761 * @return an {@code Integer} object holding the value 762 * represented by the string argument in the specified 763 * radix. 764 * @exception NumberFormatException if the {@code String} 765 * does not contain a parsable {@code int}. 766 */ 767 public static Integer valueOf(String s, int radix) throws NumberFormatException { 768 return Integer.valueOf(parseInt(s,radix)); 769 } 770 771 /** 772 * Returns an {@code Integer} object holding the 773 * value of the specified {@code String}. The argument is 774 * interpreted as representing a signed decimal integer, exactly 775 * as if the argument were given to the {@link 776 * #parseInt(java.lang.String)} method. The result is an 777 * {@code Integer} object that represents the integer value 778 * specified by the string. 779 * 780 * <p>In other words, this method returns an {@code Integer} 781 * object equal to the value of: 782 * 783 * <blockquote> 784 * {@code new Integer(Integer.parseInt(s))} 785 * </blockquote> 786 * 787 * @param s the string to be parsed. 788 * @return an {@code Integer} object holding the value 789 * represented by the string argument. 790 * @exception NumberFormatException if the string cannot be parsed 791 * as an integer. 792 */ 793 public static Integer valueOf(String s) throws NumberFormatException { 794 return Integer.valueOf(parseInt(s, 10)); 795 } 796 797 /** 798 * Cache to support the object identity semantics of autoboxing for values between 799 * -128 and 127 (inclusive) as required by JLS. 800 * 801 * The cache is initialized on first usage. The size of the cache 802 * may be controlled by the {@code -XX:AutoBoxCacheMax=<size>} option. 803 * During VM initialization, java.lang.Integer.IntegerCache.high property 804 * may be set and saved in the private system properties in the 805 * sun.misc.VM class. 806 */ 807 808 private static class IntegerCache { 809 static final int low = -128; 810 static final int high; 811 static final Integer cache[]; 812 813 static { 814 // high value may be configured by property 815 int h = 127; 816 String integerCacheHighPropValue = 817 sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high"); 818 if (integerCacheHighPropValue != null) { 819 try { 820 int i = parseInt(integerCacheHighPropValue); 821 i = Math.max(i, 127); 822 // Maximum array size is Integer.MAX_VALUE 823 h = Math.min(i, Integer.MAX_VALUE - (-low) -1); 824 } catch( NumberFormatException nfe) { 825 // If the property cannot be parsed into an int, ignore it. 826 } 827 } 828 high = h; 829 830 cache = new Integer[(high - low) + 1]; 831 int j = low; 832 for(int k = 0; k < cache.length; k++) 833 cache[k] = new Integer(j++); 834 835 // range [-128, 127] must be interned (JLS7 5.1.7) 836 assert IntegerCache.high >= 127; 837 } 838 839 private IntegerCache() {} 840 } 841 842 /** 843 * Returns an {@code Integer} instance representing the specified 844 * {@code int} value. If a new {@code Integer} instance is not 845 * required, this method should generally be used in preference to 846 * the constructor {@link #Integer(int)}, as this method is likely 847 * to yield significantly better space and time performance by 848 * caching frequently requested values. 849 * 850 * This method will always cache values in the range -128 to 127, 851 * inclusive, and may cache other values outside of this range. 852 * 853 * @param i an {@code int} value. 854 * @return an {@code Integer} instance representing {@code i}. 855 * @since 1.5 856 */ 857 public static Integer valueOf(int i) { 858 if (i >= IntegerCache.low && i <= IntegerCache.high) 859 return IntegerCache.cache[i + (-IntegerCache.low)]; 860 return new Integer(i); 861 } 862 863 /** 864 * The value of the {@code Integer}. 865 * 866 * @serial 867 */ 868 private final int value; 869 870 /** 871 * Constructs a newly allocated {@code Integer} object that 872 * represents the specified {@code int} value. 873 * 874 * @param value the value to be represented by the 875 * {@code Integer} object. 876 */ 877 public Integer(int value) { 878 this.value = value; 879 } 880 881 /** 882 * Constructs a newly allocated {@code Integer} object that 883 * represents the {@code int} value indicated by the 884 * {@code String} parameter. The string is converted to an 885 * {@code int} value in exactly the manner used by the 886 * {@code parseInt} method for radix 10. 887 * 888 * @param s the {@code String} to be converted to an 889 * {@code Integer}. 890 * @exception NumberFormatException if the {@code String} does not 891 * contain a parsable integer. 892 * @see java.lang.Integer#parseInt(java.lang.String, int) 893 */ 894 public Integer(String s) throws NumberFormatException { 895 this.value = parseInt(s, 10); 896 } 897 898 /** 899 * Returns the value of this {@code Integer} as a {@code byte} 900 * after a narrowing primitive conversion. 901 * @jls 5.1.3 Narrowing Primitive Conversions 902 */ 903 public byte byteValue() { 904 return (byte)value; 905 } 906 907 /** 908 * Returns the value of this {@code Integer} as a {@code short} 909 * after a narrowing primitive conversion. 910 * @jls 5.1.3 Narrowing Primitive Conversions 911 */ 912 public short shortValue() { 913 return (short)value; 914 } 915 916 /** 917 * Returns the value of this {@code Integer} as an 918 * {@code int}. 919 */ 920 public int intValue() { 921 return value; 922 } 923 924 /** 925 * Returns the value of this {@code Integer} as a {@code long} 926 * after a widening primitive conversion. 927 * @jls 5.1.2 Widening Primitive Conversions 928 * @see Integer#toUnsignedLong(int) 929 */ 930 public long longValue() { 931 return (long)value; 932 } 933 934 /** 935 * Returns the value of this {@code Integer} as a {@code float} 936 * after a widening primitive conversion. 937 * @jls 5.1.2 Widening Primitive Conversions 938 */ 939 public float floatValue() { 940 return (float)value; 941 } 942 943 /** 944 * Returns the value of this {@code Integer} as a {@code double} 945 * after a widening primitive conversion. 946 * @jls 5.1.2 Widening Primitive Conversions 947 */ 948 public double doubleValue() { 949 return (double)value; 950 } 951 952 /** 953 * Returns a {@code String} object representing this 954 * {@code Integer}'s value. The value is converted to signed 955 * decimal representation and returned as a string, exactly as if 956 * the integer value were given as an argument to the {@link 957 * java.lang.Integer#toString(int)} method. 958 * 959 * @return a string representation of the value of this object in 960 * base 10. 961 */ 962 public String toString() { 963 return toString(value); 964 } 965 966 /** 967 * Returns a hash code for this {@code Integer}. 968 * 969 * @return a hash code value for this object, equal to the 970 * primitive {@code int} value represented by this 971 * {@code Integer} object. 972 */ 973 @Override 974 public int hashCode() { 975 return Integer.hashCode(value); 976 } 977 978 /** 979 * Returns a hash code for a {@code int} value; compatible with 980 * {@code Integer.hashCode()}. 981 * 982 * @param value the value to hash 983 * @since 1.8 984 * 985 * @return a hash code value for a {@code int} value. 986 */ 987 public static int hashCode(int value) { 988 return value; 989 } 990 991 /** 992 * Compares this object to the specified object. The result is 993 * {@code true} if and only if the argument is not 994 * {@code null} and is an {@code Integer} object that 995 * contains the same {@code int} value as this object. 996 * 997 * @param obj the object to compare with. 998 * @return {@code true} if the objects are the same; 999 * {@code false} otherwise. 1000 */ 1001 public boolean equals(Object obj) { 1002 if (obj instanceof Integer) { 1003 return value == ((Integer)obj).intValue(); 1004 } 1005 return false; 1006 } 1007 1008 /** 1009 * Determines the integer value of the system property with the 1010 * specified name. 1011 * 1012 * <p>The first argument is treated as the name of a system 1013 * property. System properties are accessible through the {@link 1014 * java.lang.System#getProperty(java.lang.String)} method. The 1015 * string value of this property is then interpreted as an integer 1016 * value using the grammar supported by {@link Integer#decode decode} and 1017 * an {@code Integer} object representing this value is returned. 1018 * 1019 * <p>If there is no property with the specified name, if the 1020 * specified name is empty or {@code null}, or if the property 1021 * does not have the correct numeric format, then {@code null} is 1022 * returned. 1023 * 1024 * <p>In other words, this method returns an {@code Integer} 1025 * object equal to the value of: 1026 * 1027 * <blockquote> 1028 * {@code getInteger(nm, null)} 1029 * </blockquote> 1030 * 1031 * @param nm property name. 1032 * @return the {@code Integer} value of the property. 1033 * @throws SecurityException for the same reasons as 1034 * {@link System#getProperty(String) System.getProperty} 1035 * @see java.lang.System#getProperty(java.lang.String) 1036 * @see java.lang.System#getProperty(java.lang.String, java.lang.String) 1037 */ 1038 public static Integer getInteger(String nm) { 1039 return getInteger(nm, null); 1040 } 1041 1042 /** 1043 * Determines the integer value of the system property with the 1044 * specified name. 1045 * 1046 * <p>The first argument is treated as the name of a system 1047 * property. System properties are accessible through the {@link 1048 * java.lang.System#getProperty(java.lang.String)} method. The 1049 * string value of this property is then interpreted as an integer 1050 * value using the grammar supported by {@link Integer#decode decode} and 1051 * an {@code Integer} object representing this value is returned. 1052 * 1053 * <p>The second argument is the default value. An {@code Integer} object 1054 * that represents the value of the second argument is returned if there 1055 * is no property of the specified name, if the property does not have 1056 * the correct numeric format, or if the specified name is empty or 1057 * {@code null}. 1058 * 1059 * <p>In other words, this method returns an {@code Integer} object 1060 * equal to the value of: 1061 * 1062 * <blockquote> 1063 * {@code getInteger(nm, new Integer(val))} 1064 * </blockquote> 1065 * 1066 * but in practice it may be implemented in a manner such as: 1067 * 1068 * <blockquote><pre> 1069 * Integer result = getInteger(nm, null); 1070 * return (result == null) ? new Integer(val) : result; 1071 * </pre></blockquote> 1072 * 1073 * to avoid the unnecessary allocation of an {@code Integer} 1074 * object when the default value is not needed. 1075 * 1076 * @param nm property name. 1077 * @param val default value. 1078 * @return the {@code Integer} value of the property. 1079 * @throws SecurityException for the same reasons as 1080 * {@link System#getProperty(String) System.getProperty} 1081 * @see java.lang.System#getProperty(java.lang.String) 1082 * @see java.lang.System#getProperty(java.lang.String, java.lang.String) 1083 */ 1084 public static Integer getInteger(String nm, int val) { 1085 Integer result = getInteger(nm, null); 1086 return (result == null) ? Integer.valueOf(val) : result; 1087 } 1088 1089 /** 1090 * Returns the integer value of the system property with the 1091 * specified name. The first argument is treated as the name of a 1092 * system property. System properties are accessible through the 1093 * {@link java.lang.System#getProperty(java.lang.String)} method. 1094 * The string value of this property is then interpreted as an 1095 * integer value, as per the {@link Integer#decode decode} method, 1096 * and an {@code Integer} object representing this value is 1097 * returned; in summary: 1098 * 1099 * <ul><li>If the property value begins with the two ASCII characters 1100 * {@code 0x} or the ASCII character {@code #}, not 1101 * followed by a minus sign, then the rest of it is parsed as a 1102 * hexadecimal integer exactly as by the method 1103 * {@link #valueOf(java.lang.String, int)} with radix 16. 1104 * <li>If the property value begins with the ASCII character 1105 * {@code 0} followed by another character, it is parsed as an 1106 * octal integer exactly as by the method 1107 * {@link #valueOf(java.lang.String, int)} with radix 8. 1108 * <li>Otherwise, the property value is parsed as a decimal integer 1109 * exactly as by the method {@link #valueOf(java.lang.String, int)} 1110 * with radix 10. 1111 * </ul> 1112 * 1113 * <p>The second argument is the default value. The default value is 1114 * returned if there is no property of the specified name, if the 1115 * property does not have the correct numeric format, or if the 1116 * specified name is empty or {@code null}. 1117 * 1118 * @param nm property name. 1119 * @param val default value. 1120 * @return the {@code Integer} value of the property. 1121 * @throws SecurityException for the same reasons as 1122 * {@link System#getProperty(String) System.getProperty} 1123 * @see System#getProperty(java.lang.String) 1124 * @see System#getProperty(java.lang.String, java.lang.String) 1125 */ 1126 public static Integer getInteger(String nm, Integer val) { 1127 String v = null; 1128 try { 1129 v = System.getProperty(nm); 1130 } catch (IllegalArgumentException | NullPointerException e) { 1131 } 1132 if (v != null) { 1133 try { 1134 return Integer.decode(v); 1135 } catch (NumberFormatException e) { 1136 } 1137 } 1138 return val; 1139 } 1140 1141 /** 1142 * Decodes a {@code String} into an {@code Integer}. 1143 * Accepts decimal, hexadecimal, and octal numbers given 1144 * by the following grammar: 1145 * 1146 * <blockquote> 1147 * <dl> 1148 * <dt><i>DecodableString:</i> 1149 * <dd><i>Sign<sub>opt</sub> DecimalNumeral</i> 1150 * <dd><i>Sign<sub>opt</sub></i> {@code 0x} <i>HexDigits</i> 1151 * <dd><i>Sign<sub>opt</sub></i> {@code 0X} <i>HexDigits</i> 1152 * <dd><i>Sign<sub>opt</sub></i> {@code #} <i>HexDigits</i> 1153 * <dd><i>Sign<sub>opt</sub></i> {@code 0} <i>OctalDigits</i> 1154 * 1155 * <dt><i>Sign:</i> 1156 * <dd>{@code -} 1157 * <dd>{@code +} 1158 * </dl> 1159 * </blockquote> 1160 * 1161 * <i>DecimalNumeral</i>, <i>HexDigits</i>, and <i>OctalDigits</i> 1162 * are as defined in section 3.10.1 of 1163 * <cite>The Java™ Language Specification</cite>, 1164 * except that underscores are not accepted between digits. 1165 * 1166 * <p>The sequence of characters following an optional 1167 * sign and/or radix specifier ("{@code 0x}", "{@code 0X}", 1168 * "{@code #}", or leading zero) is parsed as by the {@code 1169 * Integer.parseInt} method with the indicated radix (10, 16, or 1170 * 8). This sequence of characters must represent a positive 1171 * value or a {@link NumberFormatException} will be thrown. The 1172 * result is negated if first character of the specified {@code 1173 * String} is the minus sign. No whitespace characters are 1174 * permitted in the {@code String}. 1175 * 1176 * @param nm the {@code String} to decode. 1177 * @return an {@code Integer} object holding the {@code int} 1178 * value represented by {@code nm} 1179 * @exception NumberFormatException if the {@code String} does not 1180 * contain a parsable integer. 1181 * @see java.lang.Integer#parseInt(java.lang.String, int) 1182 */ 1183 public static Integer decode(String nm) throws NumberFormatException { 1184 int radix = 10; 1185 int index = 0; 1186 boolean negative = false; 1187 Integer result; 1188 1189 if (nm.length() == 0) 1190 throw new NumberFormatException("Zero length string"); 1191 char firstChar = nm.charAt(0); 1192 // Handle sign, if present 1193 if (firstChar == '-') { 1194 negative = true; 1195 index++; 1196 } else if (firstChar == '+') 1197 index++; 1198 1199 // Handle radix specifier, if present 1200 if (nm.startsWith("0x", index) || nm.startsWith("0X", index)) { 1201 index += 2; 1202 radix = 16; 1203 } 1204 else if (nm.startsWith("#", index)) { 1205 index ++; 1206 radix = 16; 1207 } 1208 else if (nm.startsWith("0", index) && nm.length() > 1 + index) { 1209 index ++; 1210 radix = 8; 1211 } 1212 1213 if (nm.startsWith("-", index) || nm.startsWith("+", index)) 1214 throw new NumberFormatException("Sign character in wrong position"); 1215 1216 try { 1217 result = Integer.valueOf(nm.substring(index), radix); 1218 result = negative ? Integer.valueOf(-result.intValue()) : result; 1219 } catch (NumberFormatException e) { 1220 // If number is Integer.MIN_VALUE, we'll end up here. The next line 1221 // handles this case, and causes any genuine format error to be 1222 // rethrown. 1223 String constant = negative ? ("-" + nm.substring(index)) 1224 : nm.substring(index); 1225 result = Integer.valueOf(constant, radix); 1226 } 1227 return result; 1228 } 1229 1230 /** 1231 * Compares two {@code Integer} objects numerically. 1232 * 1233 * @param anotherInteger the {@code Integer} to be compared. 1234 * @return the value {@code 0} if this {@code Integer} is 1235 * equal to the argument {@code Integer}; a value less than 1236 * {@code 0} if this {@code Integer} is numerically less 1237 * than the argument {@code Integer}; and a value greater 1238 * than {@code 0} if this {@code Integer} is numerically 1239 * greater than the argument {@code Integer} (signed 1240 * comparison). 1241 * @since 1.2 1242 */ 1243 public int compareTo(Integer anotherInteger) { 1244 return compare(this.value, anotherInteger.value); 1245 } 1246 1247 /** 1248 * Compares two {@code int} values numerically. 1249 * The value returned is identical to what would be returned by: 1250 * <pre> 1251 * Integer.valueOf(x).compareTo(Integer.valueOf(y)) 1252 * </pre> 1253 * 1254 * @param x the first {@code int} to compare 1255 * @param y the second {@code int} to compare 1256 * @return the value {@code 0} if {@code x == y}; 1257 * a value less than {@code 0} if {@code x < y}; and 1258 * a value greater than {@code 0} if {@code x > y} 1259 * @since 1.7 1260 */ 1261 public static int compare(int x, int y) { 1262 return (x < y) ? -1 : ((x == y) ? 0 : 1); 1263 } 1264 1265 /** 1266 * Compares two {@code int} values numerically treating the values 1267 * as unsigned. 1268 * 1269 * @param x the first {@code int} to compare 1270 * @param y the second {@code int} to compare 1271 * @return the value {@code 0} if {@code x == y}; a value less 1272 * than {@code 0} if {@code x < y} as unsigned values; and 1273 * a value greater than {@code 0} if {@code x > y} as 1274 * unsigned values 1275 * @since 1.8 1276 */ 1277 public static int compareUnsigned(int x, int y) { 1278 return compare(x + MIN_VALUE, y + MIN_VALUE); 1279 } 1280 1281 /** 1282 * Converts the argument to a {@code long} by an unsigned 1283 * conversion. In an unsigned conversion to a {@code long}, the 1284 * high-order 32 bits of the {@code long} are zero and the 1285 * low-order 32 bits are equal to the bits of the integer 1286 * argument. 1287 * 1288 * Consequently, zero and positive {@code int} values are mapped 1289 * to a numerically equal {@code long} value and negative {@code 1290 * int} values are mapped to a {@code long} value equal to the 1291 * input plus 2<sup>32</sup>. 1292 * 1293 * @param x the value to convert to an unsigned {@code long} 1294 * @return the argument converted to {@code long} by an unsigned 1295 * conversion 1296 * @since 1.8 1297 */ 1298 public static long toUnsignedLong(int x) { 1299 return ((long) x) & 0xffffffffL; 1300 } 1301 1302 /** 1303 * Returns the unsigned quotient of dividing the first argument by 1304 * the second where each argument and the result is interpreted as 1305 * an unsigned value. 1306 * 1307 * <p>Note that in two's complement arithmetic, the three other 1308 * basic arithmetic operations of add, subtract, and multiply are 1309 * bit-wise identical if the two operands are regarded as both 1310 * being signed or both being unsigned. Therefore separate {@code 1311 * addUnsigned}, etc. methods are not provided. 1312 * 1313 * @param dividend the value to be divided 1314 * @param divisor the value doing the dividing 1315 * @return the unsigned quotient of the first argument divided by 1316 * the second argument 1317 * @see #remainderUnsigned 1318 * @since 1.8 1319 */ 1320 public static int divideUnsigned(int dividend, int divisor) { 1321 // In lieu of tricky code, for now just use long arithmetic. 1322 return (int)(toUnsignedLong(dividend) / toUnsignedLong(divisor)); 1323 } 1324 1325 /** 1326 * Returns the unsigned remainder from dividing the first argument 1327 * by the second where each argument and the result is interpreted 1328 * as an unsigned value. 1329 * 1330 * @param dividend the value to be divided 1331 * @param divisor the value doing the dividing 1332 * @return the unsigned remainder of the first argument divided by 1333 * the second argument 1334 * @see #divideUnsigned 1335 * @since 1.8 1336 */ 1337 public static int remainderUnsigned(int dividend, int divisor) { 1338 // In lieu of tricky code, for now just use long arithmetic. 1339 return (int)(toUnsignedLong(dividend) % toUnsignedLong(divisor)); 1340 } 1341 1342 1343 // Bit twiddling 1344 1345 /** 1346 * The number of bits used to represent an {@code int} value in two's 1347 * complement binary form. 1348 * 1349 * @since 1.5 1350 */ 1351 @Native public static final int SIZE = 32; 1352 1353 /** 1354 * The number of bytes used to represent a {@code int} value in two's 1355 * complement binary form. 1356 * 1357 * @since 1.8 1358 */ 1359 public static final int BYTES = SIZE / Byte.SIZE; 1360 1361 /** 1362 * Returns an {@code int} value with at most a single one-bit, in the 1363 * position of the highest-order ("leftmost") one-bit in the specified 1364 * {@code int} value. Returns zero if the specified value has no 1365 * one-bits in its two's complement binary representation, that is, if it 1366 * is equal to zero. 1367 * 1368 * @param i the value whose highest one bit is to be computed 1369 * @return an {@code int} value with a single one-bit, in the position 1370 * of the highest-order one-bit in the specified value, or zero if 1371 * the specified value is itself equal to zero. 1372 * @since 1.5 1373 */ 1374 public static int highestOneBit(int i) { 1375 // HD, Figure 3-1 1376 i |= (i >> 1); 1377 i |= (i >> 2); 1378 i |= (i >> 4); 1379 i |= (i >> 8); 1380 i |= (i >> 16); 1381 return i - (i >>> 1); 1382 } 1383 1384 /** 1385 * Returns an {@code int} value with at most a single one-bit, in the 1386 * position of the lowest-order ("rightmost") one-bit in the specified 1387 * {@code int} value. Returns zero if the specified value has no 1388 * one-bits in its two's complement binary representation, that is, if it 1389 * is equal to zero. 1390 * 1391 * @param i the value whose lowest one bit is to be computed 1392 * @return an {@code int} value with a single one-bit, in the position 1393 * of the lowest-order one-bit in the specified value, or zero if 1394 * the specified value is itself equal to zero. 1395 * @since 1.5 1396 */ 1397 public static int lowestOneBit(int i) { 1398 // HD, Section 2-1 1399 return i & -i; 1400 } 1401 1402 /** 1403 * Returns the number of zero bits preceding the highest-order 1404 * ("leftmost") one-bit in the two's complement binary representation 1405 * of the specified {@code int} value. Returns 32 if the 1406 * specified value has no one-bits in its two's complement representation, 1407 * in other words if it is equal to zero. 1408 * 1409 * <p>Note that this method is closely related to the logarithm base 2. 1410 * For all positive {@code int} values x: 1411 * <ul> 1412 * <li>floor(log<sub>2</sub>(x)) = {@code 31 - numberOfLeadingZeros(x)} 1413 * <li>ceil(log<sub>2</sub>(x)) = {@code 32 - numberOfLeadingZeros(x - 1)} 1414 * </ul> 1415 * 1416 * @param i the value whose number of leading zeros is to be computed 1417 * @return the number of zero bits preceding the highest-order 1418 * ("leftmost") one-bit in the two's complement binary representation 1419 * of the specified {@code int} value, or 32 if the value 1420 * is equal to zero. 1421 * @since 1.5 1422 */ 1423 public static int numberOfLeadingZeros(int i) { 1424 // HD, Figure 5-6 1425 if (i == 0) 1426 return 32; 1427 int n = 1; 1428 if (i >>> 16 == 0) { n += 16; i <<= 16; } 1429 if (i >>> 24 == 0) { n += 8; i <<= 8; } 1430 if (i >>> 28 == 0) { n += 4; i <<= 4; } 1431 if (i >>> 30 == 0) { n += 2; i <<= 2; } 1432 n -= i >>> 31; 1433 return n; 1434 } 1435 1436 /** 1437 * Returns the number of zero bits following the lowest-order ("rightmost") 1438 * one-bit in the two's complement binary representation of the specified 1439 * {@code int} value. Returns 32 if the specified value has no 1440 * one-bits in its two's complement representation, in other words if it is 1441 * equal to zero. 1442 * 1443 * @param i the value whose number of trailing zeros is to be computed 1444 * @return the number of zero bits following the lowest-order ("rightmost") 1445 * one-bit in the two's complement binary representation of the 1446 * specified {@code int} value, or 32 if the value is equal 1447 * to zero. 1448 * @since 1.5 1449 */ numberOfTrailingZeros(int i)1450 public static int numberOfTrailingZeros(int i) { 1451 // HD, Figure 5-14 1452 int y; 1453 if (i == 0) return 32; 1454 int n = 31; 1455 y = i <<16; if (y != 0) { n = n -16; i = y; } 1456 y = i << 8; if (y != 0) { n = n - 8; i = y; } 1457 y = i << 4; if (y != 0) { n = n - 4; i = y; } 1458 y = i << 2; if (y != 0) { n = n - 2; i = y; } 1459 return n - ((i << 1) >>> 31); 1460 } 1461 1462 /** 1463 * Returns the number of one-bits in the two's complement binary 1464 * representation of the specified {@code int} value. This function is 1465 * sometimes referred to as the <i>population count</i>. 1466 * 1467 * @param i the value whose bits are to be counted 1468 * @return the number of one-bits in the two's complement binary 1469 * representation of the specified {@code int} value. 1470 * @since 1.5 1471 */ bitCount(int i)1472 public static int bitCount(int i) { 1473 // HD, Figure 5-2 1474 i = i - ((i >>> 1) & 0x55555555); 1475 i = (i & 0x33333333) + ((i >>> 2) & 0x33333333); 1476 i = (i + (i >>> 4)) & 0x0f0f0f0f; 1477 i = i + (i >>> 8); 1478 i = i + (i >>> 16); 1479 return i & 0x3f; 1480 } 1481 1482 /** 1483 * Returns the value obtained by rotating the two's complement binary 1484 * representation of the specified {@code int} value left by the 1485 * specified number of bits. (Bits shifted out of the left hand, or 1486 * high-order, side reenter on the right, or low-order.) 1487 * 1488 * <p>Note that left rotation with a negative distance is equivalent to 1489 * right rotation: {@code rotateLeft(val, -distance) == rotateRight(val, 1490 * distance)}. Note also that rotation by any multiple of 32 is a 1491 * no-op, so all but the last five bits of the rotation distance can be 1492 * ignored, even if the distance is negative: {@code rotateLeft(val, 1493 * distance) == rotateLeft(val, distance & 0x1F)}. 1494 * 1495 * @param i the value whose bits are to be rotated left 1496 * @param distance the number of bit positions to rotate left 1497 * @return the value obtained by rotating the two's complement binary 1498 * representation of the specified {@code int} value left by the 1499 * specified number of bits. 1500 * @since 1.5 1501 */ rotateLeft(int i, int distance)1502 public static int rotateLeft(int i, int distance) { 1503 return (i << distance) | (i >>> -distance); 1504 } 1505 1506 /** 1507 * Returns the value obtained by rotating the two's complement binary 1508 * representation of the specified {@code int} value right by the 1509 * specified number of bits. (Bits shifted out of the right hand, or 1510 * low-order, side reenter on the left, or high-order.) 1511 * 1512 * <p>Note that right rotation with a negative distance is equivalent to 1513 * left rotation: {@code rotateRight(val, -distance) == rotateLeft(val, 1514 * distance)}. Note also that rotation by any multiple of 32 is a 1515 * no-op, so all but the last five bits of the rotation distance can be 1516 * ignored, even if the distance is negative: {@code rotateRight(val, 1517 * distance) == rotateRight(val, distance & 0x1F)}. 1518 * 1519 * @param i the value whose bits are to be rotated right 1520 * @param distance the number of bit positions to rotate right 1521 * @return the value obtained by rotating the two's complement binary 1522 * representation of the specified {@code int} value right by the 1523 * specified number of bits. 1524 * @since 1.5 1525 */ rotateRight(int i, int distance)1526 public static int rotateRight(int i, int distance) { 1527 return (i >>> distance) | (i << -distance); 1528 } 1529 1530 /** 1531 * Returns the value obtained by reversing the order of the bits in the 1532 * two's complement binary representation of the specified {@code int} 1533 * value. 1534 * 1535 * @param i the value to be reversed 1536 * @return the value obtained by reversing order of the bits in the 1537 * specified {@code int} value. 1538 * @since 1.5 1539 */ reverse(int i)1540 public static int reverse(int i) { 1541 // HD, Figure 7-1 1542 i = (i & 0x55555555) << 1 | (i >>> 1) & 0x55555555; 1543 i = (i & 0x33333333) << 2 | (i >>> 2) & 0x33333333; 1544 i = (i & 0x0f0f0f0f) << 4 | (i >>> 4) & 0x0f0f0f0f; 1545 i = (i << 24) | ((i & 0xff00) << 8) | 1546 ((i >>> 8) & 0xff00) | (i >>> 24); 1547 return i; 1548 } 1549 1550 /** 1551 * Returns the signum function of the specified {@code int} value. (The 1552 * return value is -1 if the specified value is negative; 0 if the 1553 * specified value is zero; and 1 if the specified value is positive.) 1554 * 1555 * @param i the value whose signum is to be computed 1556 * @return the signum function of the specified {@code int} value. 1557 * @since 1.5 1558 */ signum(int i)1559 public static int signum(int i) { 1560 // HD, Section 2-7 1561 return (i >> 31) | (-i >>> 31); 1562 } 1563 1564 /** 1565 * Returns the value obtained by reversing the order of the bytes in the 1566 * two's complement representation of the specified {@code int} value. 1567 * 1568 * @param i the value whose bytes are to be reversed 1569 * @return the value obtained by reversing the bytes in the specified 1570 * {@code int} value. 1571 * @since 1.5 1572 */ reverseBytes(int i)1573 public static int reverseBytes(int i) { 1574 return ((i >>> 24) ) | 1575 ((i >> 8) & 0xFF00) | 1576 ((i << 8) & 0xFF0000) | 1577 ((i << 24)); 1578 } 1579 1580 /** 1581 * Adds two integers together as per the + operator. 1582 * 1583 * @param a the first operand 1584 * @param b the second operand 1585 * @return the sum of {@code a} and {@code b} 1586 * @see java.util.function.BinaryOperator 1587 * @since 1.8 1588 */ sum(int a, int b)1589 public static int sum(int a, int b) { 1590 return a + b; 1591 } 1592 1593 /** 1594 * Returns the greater of two {@code int} values 1595 * as if by calling {@link Math#max(int, int) Math.max}. 1596 * 1597 * @param a the first operand 1598 * @param b the second operand 1599 * @return the greater of {@code a} and {@code b} 1600 * @see java.util.function.BinaryOperator 1601 * @since 1.8 1602 */ max(int a, int b)1603 public static int max(int a, int b) { 1604 return Math.max(a, b); 1605 } 1606 1607 /** 1608 * Returns the smaller of two {@code int} values 1609 * as if by calling {@link Math#min(int, int) Math.min}. 1610 * 1611 * @param a the first operand 1612 * @param b the second operand 1613 * @return the smaller of {@code a} and {@code b} 1614 * @see java.util.function.BinaryOperator 1615 * @since 1.8 1616 */ min(int a, int b)1617 public static int min(int a, int b) { 1618 return Math.min(a, b); 1619 } 1620 1621 /** use serialVersionUID from JDK 1.0.2 for interoperability */ 1622 @Native private static final long serialVersionUID = 1360826667806852920L; 1623 } 1624