1 /* 2 * Copyright (c) 1994, 2023, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 26 package java.lang; 27 28 import jdk.internal.misc.CDS; 29 import jdk.internal.misc.VM; 30 import jdk.internal.vm.annotation.ForceInline; 31 import jdk.internal.vm.annotation.IntrinsicCandidate; 32 import jdk.internal.vm.annotation.Stable; 33 34 import java.lang.annotation.Native; 35 import java.lang.constant.Constable; 36 import java.lang.constant.ConstantDesc; 37 import java.lang.invoke.MethodHandles; 38 import java.util.Objects; 39 import java.util.Optional; 40 41 import static java.lang.Character.digit; 42 import static java.lang.String.COMPACT_STRINGS; 43 import static java.lang.String.LATIN1; 44 import static java.lang.String.UTF16; 45 46 /** 47 * The {@code Integer} class wraps a value of the primitive type 48 * {@code int} in an object. An object of type {@code Integer} 49 * contains a single field whose type is {@code int}. 50 * 51 * <p>In addition, this class provides several methods for converting 52 * an {@code int} to a {@code String} and a {@code String} to an 53 * {@code int}, as well as other constants and methods useful when 54 * dealing with an {@code int}. 55 * 56 * <p>This is a <a href="{@docRoot}/java.base/java/lang/doc-files/ValueBased.html">value-based</a> 57 * class; programmers should treat instances that are 58 * {@linkplain #equals(Object) equal} as interchangeable and should not 59 * use instances for synchronization, or unpredictable behavior may 60 * occur. For example, in a future release, synchronization may fail. 61 * 62 * <p>Implementation note: The implementations of the "bit twiddling" 63 * methods (such as {@link #highestOneBit(int) highestOneBit} and 64 * {@link #numberOfTrailingZeros(int) numberOfTrailingZeros}) are 65 * based on material from Henry S. Warren, Jr.'s <i>Hacker's 66 * Delight</i>, (Addison Wesley, 2002). 67 * 68 * @author Lee Boynton 69 * @author Arthur van Hoff 70 * @author Josh Bloch 71 * @author Joseph D. Darcy 72 * @since 1.0 73 */ 74 @jdk.internal.ValueBased 75 public final class Integer extends Number 76 implements Comparable<Integer>, Constable, ConstantDesc { 77 /** 78 * A constant holding the minimum value an {@code int} can 79 * have, -2<sup>31</sup>. 80 */ 81 @Native public static final int MIN_VALUE = 0x80000000; 82 83 /** 84 * A constant holding the maximum value an {@code int} can 85 * have, 2<sup>31</sup>-1. 86 */ 87 @Native public static final int MAX_VALUE = 0x7fffffff; 88 89 /** 90 * The {@code Class} instance representing the primitive type 91 * {@code int}. 92 * 93 * @since 1.1 94 */ 95 @SuppressWarnings("unchecked") 96 public static final Class<Integer> TYPE = (Class<Integer>) Class.getPrimitiveClass("int"); 97 98 /** 99 * All possible chars for representing a number as a String 100 */ 101 static final char[] digits = { 102 '0' , '1' , '2' , '3' , '4' , '5' , 103 '6' , '7' , '8' , '9' , 'a' , 'b' , 104 'c' , 'd' , 'e' , 'f' , 'g' , 'h' , 105 'i' , 'j' , 'k' , 'l' , 'm' , 'n' , 106 'o' , 'p' , 'q' , 'r' , 's' , 't' , 107 'u' , 'v' , 'w' , 'x' , 'y' , 'z' 108 }; 109 110 /** 111 * Returns a string representation of the first argument in the 112 * radix specified by the second argument. 113 * 114 * <p>If the radix is smaller than {@code Character.MIN_RADIX} 115 * or larger than {@code Character.MAX_RADIX}, then the radix 116 * {@code 10} is used instead. 117 * 118 * <p>If the first argument is negative, the first element of the 119 * result is the ASCII minus character {@code '-'} 120 * ({@code '\u005Cu002D'}). If the first argument is not 121 * negative, no sign character appears in the result. 122 * 123 * <p>The remaining characters of the result represent the magnitude 124 * of the first argument. If the magnitude is zero, it is 125 * represented by a single zero character {@code '0'} 126 * ({@code '\u005Cu0030'}); otherwise, the first character of 127 * the representation of the magnitude will not be the zero 128 * character. The following ASCII characters are used as digits: 129 * 130 * <blockquote> 131 * {@code 0123456789abcdefghijklmnopqrstuvwxyz} 132 * </blockquote> 133 * 134 * These are {@code '\u005Cu0030'} through 135 * {@code '\u005Cu0039'} and {@code '\u005Cu0061'} through 136 * {@code '\u005Cu007A'}. If {@code radix} is 137 * <var>N</var>, then the first <var>N</var> of these characters 138 * are used as radix-<var>N</var> digits in the order shown. Thus, 139 * the digits for hexadecimal (radix 16) are 140 * {@code 0123456789abcdef}. If uppercase letters are 141 * desired, the {@link java.lang.String#toUpperCase()} method may 142 * be called on the result: 143 * 144 * <blockquote> 145 * {@code Integer.toString(n, 16).toUpperCase()} 146 * </blockquote> 147 * 148 * @param i an integer to be converted to a string. 149 * @param radix the radix to use in the string representation. 150 * @return a string representation of the argument in the specified radix. 151 * @see java.lang.Character#MAX_RADIX 152 * @see java.lang.Character#MIN_RADIX 153 */ 154 public static String toString(int i, int radix) { 155 if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX) 156 radix = 10; 157 158 /* Use the faster version */ 159 if (radix == 10) { 160 return toString(i); 161 } 162 163 if (COMPACT_STRINGS) { 164 byte[] buf = new byte[33]; 165 boolean negative = (i < 0); 166 int charPos = 32; 167 168 if (!negative) { 169 i = -i; 170 } 171 172 while (i <= -radix) { 173 buf[charPos--] = (byte)digits[-(i % radix)]; 174 i = i / radix; 175 } 176 buf[charPos] = (byte)digits[-i]; 177 178 if (negative) { 179 buf[--charPos] = '-'; 180 } 181 182 return StringLatin1.newString(buf, charPos, (33 - charPos)); 183 } 184 return toStringUTF16(i, radix); 185 } 186 187 private static String toStringUTF16(int i, int radix) { 188 byte[] buf = new byte[33 * 2]; 189 boolean negative = (i < 0); 190 int charPos = 32; 191 if (!negative) { 192 i = -i; 193 } 194 while (i <= -radix) { 195 StringUTF16.putChar(buf, charPos--, digits[-(i % radix)]); 196 i = i / radix; 197 } 198 StringUTF16.putChar(buf, charPos, digits[-i]); 199 200 if (negative) { 201 StringUTF16.putChar(buf, --charPos, '-'); 202 } 203 return StringUTF16.newString(buf, charPos, (33 - charPos)); 204 } 205 206 /** 207 * Returns a string representation of the first argument as an 208 * unsigned integer value in the radix specified by the second 209 * argument. 210 * 211 * <p>If the radix is smaller than {@code Character.MIN_RADIX} 212 * or larger than {@code Character.MAX_RADIX}, then the radix 213 * {@code 10} is used instead. 214 * 215 * <p>Note that since the first argument is treated as an unsigned 216 * value, no leading sign character is printed. 217 * 218 * <p>If the magnitude is zero, it is represented by a single zero 219 * character {@code '0'} ({@code '\u005Cu0030'}); otherwise, 220 * the first character of the representation of the magnitude will 221 * not be the zero character. 222 * 223 * <p>The behavior of radixes and the characters used as digits 224 * are the same as {@link #toString(int, int) toString}. 225 * 226 * @param i an integer to be converted to an unsigned string. 227 * @param radix the radix to use in the string representation. 228 * @return an unsigned string representation of the argument in the specified radix. 229 * @see #toString(int, int) 230 * @since 1.8 231 */ 232 public static String toUnsignedString(int i, int radix) { 233 return Long.toUnsignedString(toUnsignedLong(i), radix); 234 } 235 236 /** 237 * Returns a string representation of the integer argument as an 238 * unsigned integer in base 16. 239 * 240 * <p>The unsigned integer value is the argument plus 2<sup>32</sup> 241 * if the argument is negative; otherwise, it is equal to the 242 * argument. This value is converted to a string of ASCII digits 243 * in hexadecimal (base 16) with no extra leading 244 * {@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, 16)}. 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 hexadecimal digits: 256 * 257 * <blockquote> 258 * {@code 0123456789abcdef} 259 * </blockquote> 260 * 261 * These are the characters {@code '\u005Cu0030'} through 262 * {@code '\u005Cu0039'} and {@code '\u005Cu0061'} through 263 * {@code '\u005Cu0066'}. If uppercase letters are 264 * desired, the {@link java.lang.String#toUpperCase()} method may 265 * be called on the result: 266 * 267 * <blockquote> 268 * {@code Integer.toHexString(n).toUpperCase()} 269 * </blockquote> 270 * 271 * @apiNote 272 * The {@link java.util.HexFormat} class provides formatting and parsing 273 * of byte arrays and primitives to return a string or adding to an {@link Appendable}. 274 * {@code HexFormat} formats and parses uppercase or lowercase hexadecimal characters, 275 * with leading zeros and for byte arrays includes for each byte 276 * a delimiter, prefix, and suffix. 277 * 278 * @param i an integer to be converted to a string. 279 * @return the string representation of the unsigned integer value 280 * represented by the argument in hexadecimal (base 16). 281 * @see java.util.HexFormat 282 * @see #parseUnsignedInt(String, int) 283 * @see #toUnsignedString(int, int) 284 * @since 1.0.2 285 */ 286 public static String toHexString(int i) { 287 return toUnsignedString0(i, 4); 288 } 289 290 /** 291 * Returns a string representation of the integer argument as an 292 * unsigned integer in base 8. 293 * 294 * <p>The unsigned integer value is the argument plus 2<sup>32</sup> 295 * if the argument is negative; otherwise, it is equal to the 296 * argument. This value is converted to a string of ASCII digits 297 * in octal (base 8) with no extra leading {@code 0}s. 298 * 299 * <p>The value of the argument can be recovered from the returned 300 * string {@code s} by calling {@link 301 * Integer#parseUnsignedInt(String, int) 302 * Integer.parseUnsignedInt(s, 8)}. 303 * 304 * <p>If the unsigned magnitude is zero, it is represented by a 305 * single zero character {@code '0'} ({@code '\u005Cu0030'}); 306 * otherwise, the first character of the representation of the 307 * unsigned magnitude will not be the zero character. The 308 * following characters are used as octal digits: 309 * 310 * <blockquote> 311 * {@code 01234567} 312 * </blockquote> 313 * 314 * These are the characters {@code '\u005Cu0030'} through 315 * {@code '\u005Cu0037'}. 316 * 317 * @param i an integer to be converted to a string. 318 * @return the string representation of the unsigned integer value 319 * represented by the argument in octal (base 8). 320 * @see #parseUnsignedInt(String, int) 321 * @see #toUnsignedString(int, int) 322 * @since 1.0.2 323 */ 324 public static String toOctalString(int i) { 325 return toUnsignedString0(i, 3); 326 } 327 328 /** 329 * Returns a string representation of the integer argument as an 330 * unsigned integer in base 2. 331 * 332 * <p>The unsigned integer value is the argument plus 2<sup>32</sup> 333 * if the argument is negative; otherwise it is equal to the 334 * argument. This value is converted to a string of ASCII digits 335 * in binary (base 2) with no extra leading {@code 0}s. 336 * 337 * <p>The value of the argument can be recovered from the returned 338 * string {@code s} by calling {@link 339 * Integer#parseUnsignedInt(String, int) 340 * Integer.parseUnsignedInt(s, 2)}. 341 * 342 * <p>If the unsigned magnitude is zero, it is represented by a 343 * single zero character {@code '0'} ({@code '\u005Cu0030'}); 344 * otherwise, the first character of the representation of the 345 * unsigned magnitude will not be the zero character. The 346 * characters {@code '0'} ({@code '\u005Cu0030'}) and {@code 347 * '1'} ({@code '\u005Cu0031'}) are used as binary digits. 348 * 349 * @param i an integer to be converted to a string. 350 * @return the string representation of the unsigned integer value 351 * represented by the argument in binary (base 2). 352 * @see #parseUnsignedInt(String, int) 353 * @see #toUnsignedString(int, int) 354 * @since 1.0.2 355 */ 356 public static String toBinaryString(int i) { 357 return toUnsignedString0(i, 1); 358 } 359 360 /** 361 * Convert the integer to an unsigned number. 362 */ 363 private static String toUnsignedString0(int val, int shift) { 364 // assert shift > 0 && shift <=5 : "Illegal shift value"; 365 int mag = Integer.SIZE - Integer.numberOfLeadingZeros(val); 366 int chars = Math.max(((mag + (shift - 1)) / shift), 1); 367 if (COMPACT_STRINGS) { 368 byte[] buf = new byte[chars]; 369 formatUnsignedInt(val, shift, buf, chars); 370 return new String(buf, LATIN1); 371 } else { 372 byte[] buf = new byte[chars * 2]; 373 formatUnsignedIntUTF16(val, shift, buf, chars); 374 return new String(buf, UTF16); 375 } 376 } 377 378 /** 379 * Format an {@code int} (treated as unsigned) into a byte buffer (LATIN1 version). If 380 * {@code len} exceeds the formatted ASCII representation of {@code val}, 381 * {@code buf} will be padded with leading zeroes. 382 * 383 * @param val the unsigned int to format 384 * @param shift the log2 of the base to format in (4 for hex, 3 for octal, 1 for binary) 385 * @param buf the byte buffer to write to 386 * @param len the number of characters to write 387 */ 388 private static void formatUnsignedInt(int val, int shift, byte[] buf, int len) { 389 int charPos = len; 390 int radix = 1 << shift; 391 int mask = radix - 1; 392 do { 393 buf[--charPos] = (byte)Integer.digits[val & mask]; 394 val >>>= shift; 395 } while (charPos > 0); 396 } 397 398 /** 399 * Format an {@code int} (treated as unsigned) into a byte buffer (UTF16 version). If 400 * {@code len} exceeds the formatted ASCII representation of {@code val}, 401 * {@code buf} will be padded with leading zeroes. 402 * 403 * @param val the unsigned int to format 404 * @param shift the log2 of the base to format in (4 for hex, 3 for octal, 1 for binary) 405 * @param buf the byte buffer to write to 406 * @param len the number of characters to write 407 */ 408 private static void formatUnsignedIntUTF16(int val, int shift, byte[] buf, int len) { 409 int charPos = len; 410 int radix = 1 << shift; 411 int mask = radix - 1; 412 do { 413 StringUTF16.putChar(buf, --charPos, Integer.digits[val & mask]); 414 val >>>= shift; 415 } while (charPos > 0); 416 } 417 418 /** 419 * Returns a {@code String} object representing the 420 * specified integer. The argument is converted to signed decimal 421 * representation and returned as a string, exactly as if the 422 * argument and radix 10 were given as arguments to the {@link 423 * #toString(int, int)} method. 424 * 425 * @param i an integer to be converted. 426 * @return a string representation of the argument in base 10. 427 */ 428 @IntrinsicCandidate 429 public static String toString(int i) { 430 int size = stringSize(i); 431 if (COMPACT_STRINGS) { 432 byte[] buf = new byte[size]; 433 StringLatin1.getChars(i, size, buf); 434 return new String(buf, LATIN1); 435 } else { 436 byte[] buf = new byte[size * 2]; 437 StringUTF16.getChars(i, size, buf); 438 return new String(buf, UTF16); 439 } 440 } 441 442 /** 443 * Returns a string representation of the argument as an unsigned 444 * decimal value. 445 * 446 * The argument is converted to unsigned decimal representation 447 * and returned as a string exactly as if the argument and radix 448 * 10 were given as arguments to the {@link #toUnsignedString(int, 449 * int)} method. 450 * 451 * @param i an integer to be converted to an unsigned string. 452 * @return an unsigned string representation of the argument. 453 * @see #toUnsignedString(int, int) 454 * @since 1.8 455 */ 456 public static String toUnsignedString(int i) { 457 return Long.toString(toUnsignedLong(i)); 458 } 459 460 /** 461 * Returns the string representation size for a given int value. 462 * 463 * @param x int value 464 * @return string size 465 * 466 * @implNote There are other ways to compute this: e.g. binary search, 467 * but values are biased heavily towards zero, and therefore linear search 468 * wins. The iteration results are also routinely inlined in the generated 469 * code after loop unrolling. 470 */ 471 static int stringSize(int x) { 472 int d = 1; 473 if (x >= 0) { 474 d = 0; 475 x = -x; 476 } 477 int p = -10; 478 for (int i = 1; i < 10; i++) { 479 if (x > p) 480 return i + d; 481 p = 10 * p; 482 } 483 return 10 + d; 484 } 485 486 /** 487 * Parses the string argument as a signed integer in the radix 488 * specified by the second argument. The characters in the string 489 * must all be digits of the specified radix (as determined by 490 * whether {@link java.lang.Character#digit(char, int)} returns a 491 * nonnegative value), except that the first character may be an 492 * ASCII minus sign {@code '-'} ({@code '\u005Cu002D'}) to 493 * indicate a negative value or an ASCII plus sign {@code '+'} 494 * ({@code '\u005Cu002B'}) to indicate a positive value. The 495 * resulting integer value is returned. 496 * 497 * <p>An exception of type {@code NumberFormatException} is 498 * thrown if any of the following situations occurs: 499 * <ul> 500 * <li>The first argument is {@code null} or is a string of 501 * length zero. 502 * 503 * <li>The radix is either smaller than 504 * {@link java.lang.Character#MIN_RADIX} or 505 * larger than {@link java.lang.Character#MAX_RADIX}. 506 * 507 * <li>Any character of the string is not a digit of the specified 508 * radix, except that the first character may be a minus sign 509 * {@code '-'} ({@code '\u005Cu002D'}) or plus sign 510 * {@code '+'} ({@code '\u005Cu002B'}) provided that the 511 * string is longer than length 1. 512 * 513 * <li>The value represented by the string is not a value of type 514 * {@code int}. 515 * </ul> 516 * 517 * <p>Examples: 518 * <blockquote><pre> 519 * parseInt("0", 10) returns 0 520 * parseInt("473", 10) returns 473 521 * parseInt("+42", 10) returns 42 522 * parseInt("-0", 10) returns 0 523 * parseInt("-FF", 16) returns -255 524 * parseInt("1100110", 2) returns 102 525 * parseInt("2147483647", 10) returns 2147483647 526 * parseInt("-2147483648", 10) returns -2147483648 527 * parseInt("2147483648", 10) throws a NumberFormatException 528 * parseInt("99", 8) throws a NumberFormatException 529 * parseInt("Kona", 10) throws a NumberFormatException 530 * parseInt("Kona", 27) returns 411787 531 * </pre></blockquote> 532 * 533 * @param s the {@code String} containing the integer 534 * representation to be parsed 535 * @param radix the radix to be used while parsing {@code s}. 536 * @return the integer represented by the string argument in the 537 * specified radix. 538 * @throws NumberFormatException if the {@code String} 539 * does not contain a parsable {@code int}. 540 */ 541 public static int parseInt(String s, int radix) 542 throws NumberFormatException { 543 /* 544 * WARNING: This method may be invoked early during VM initialization 545 * before IntegerCache is initialized. Care must be taken to not use 546 * the valueOf method. 547 */ 548 549 if (s == null) { 550 throw new NumberFormatException("Cannot parse null string"); 551 } 552 553 if (radix < Character.MIN_RADIX) { 554 throw new NumberFormatException(String.format( 555 "radix %s less than Character.MIN_RADIX", radix)); 556 } 557 558 if (radix > Character.MAX_RADIX) { 559 throw new NumberFormatException(String.format( 560 "radix %s greater than Character.MAX_RADIX", radix)); 561 } 562 563 int len = s.length(); 564 if (len == 0) { 565 throw NumberFormatException.forInputString("", radix); 566 } 567 int digit = ~0xFF; 568 int i = 0; 569 char firstChar = s.charAt(i++); 570 if (firstChar != '-' && firstChar != '+') { 571 digit = digit(firstChar, radix); 572 } 573 if (digit >= 0 || digit == ~0xFF && len > 1) { 574 int limit = firstChar != '-' ? MIN_VALUE + 1 : MIN_VALUE; 575 int multmin = limit / radix; 576 int result = -(digit & 0xFF); 577 boolean inRange = true; 578 /* Accumulating negatively avoids surprises near MAX_VALUE */ 579 while (i < len && (digit = digit(s.charAt(i++), radix)) >= 0 580 && (inRange = result > multmin 581 || result == multmin && digit <= radix * multmin - limit)) { 582 result = radix * result - digit; 583 } 584 if (inRange && i == len && digit >= 0) { 585 return firstChar != '-' ? -result : result; 586 } 587 } 588 throw NumberFormatException.forInputString(s, radix); 589 } 590 591 /** 592 * Parses the {@link CharSequence} argument as a signed {@code int} in the 593 * specified {@code radix}, beginning at the specified {@code beginIndex} 594 * and extending to {@code endIndex - 1}. 595 * 596 * <p>The method does not take steps to guard against the 597 * {@code CharSequence} being mutated while parsing. 598 * 599 * @param s the {@code CharSequence} containing the {@code int} 600 * representation to be parsed 601 * @param beginIndex the beginning index, inclusive. 602 * @param endIndex the ending index, exclusive. 603 * @param radix the radix to be used while parsing {@code s}. 604 * @return the signed {@code int} represented by the subsequence in 605 * the specified radix. 606 * @throws NullPointerException if {@code s} is null. 607 * @throws IndexOutOfBoundsException if {@code beginIndex} is 608 * negative, or if {@code beginIndex} is greater than 609 * {@code endIndex} or if {@code endIndex} is greater than 610 * {@code s.length()}. 611 * @throws NumberFormatException if the {@code CharSequence} does not 612 * contain a parsable {@code int} in the specified 613 * {@code radix}, or if {@code radix} is either smaller than 614 * {@link java.lang.Character#MIN_RADIX} or larger than 615 * {@link java.lang.Character#MAX_RADIX}. 616 * @since 9 617 */ 618 public static int parseInt(CharSequence s, int beginIndex, int endIndex, int radix) 619 throws NumberFormatException { 620 Objects.requireNonNull(s); 621 Objects.checkFromToIndex(beginIndex, endIndex, s.length()); 622 623 if (radix < Character.MIN_RADIX) { 624 throw new NumberFormatException(String.format( 625 "radix %s less than Character.MIN_RADIX", radix)); 626 } 627 628 if (radix > Character.MAX_RADIX) { 629 throw new NumberFormatException(String.format( 630 "radix %s greater than Character.MAX_RADIX", radix)); 631 } 632 633 /* 634 * While s can be concurrently modified, it is ensured that each 635 * of its characters is read at most once, from lower to higher indices. 636 * This is obtained by reading them using the pattern s.charAt(i++), 637 * and by not updating i anywhere else. 638 */ 639 if (beginIndex == endIndex) { 640 throw NumberFormatException.forInputString("", radix); 641 } 642 int digit = ~0xFF; 643 int i = beginIndex; 644 char firstChar = s.charAt(i++); 645 if (firstChar != '-' && firstChar != '+') { 646 digit = digit(firstChar, radix); 647 } 648 if (digit >= 0 || digit == ~0xFF && endIndex - beginIndex > 1) { 649 int limit = firstChar != '-' ? MIN_VALUE + 1 : MIN_VALUE; 650 int multmin = limit / radix; 651 int result = -(digit & 0xFF); 652 boolean inRange = true; 653 /* Accumulating negatively avoids surprises near MAX_VALUE */ 654 while (i < endIndex && (digit = digit(s.charAt(i++), radix)) >= 0 655 && (inRange = result > multmin 656 || result == multmin && digit <= radix * multmin - limit)) { 657 result = radix * result - digit; 658 } 659 if (inRange && i == endIndex && digit >= 0) { 660 return firstChar != '-' ? -result : result; 661 } 662 } 663 throw NumberFormatException.forCharSequence(s, beginIndex, 664 endIndex, i - (digit < -1 ? 0 : 1)); 665 } 666 667 /** 668 * Parses the string argument as a signed decimal integer. The 669 * characters in the string must all be decimal digits, except 670 * that the first character may be an ASCII minus sign {@code '-'} 671 * ({@code '\u005Cu002D'}) to indicate a negative value or an 672 * ASCII plus sign {@code '+'} ({@code '\u005Cu002B'}) to 673 * indicate a positive value. The resulting integer value is 674 * returned, exactly as if the argument and the radix 10 were 675 * given as arguments to the {@link #parseInt(java.lang.String, 676 * int)} method. 677 * 678 * @param s a {@code String} containing the {@code int} 679 * representation to be parsed 680 * @return the integer value represented by the argument in decimal. 681 * @throws NumberFormatException if the string does not contain a 682 * parsable integer. 683 */ 684 public static int parseInt(String s) throws NumberFormatException { 685 return parseInt(s, 10); 686 } 687 688 /** 689 * Parses the string argument as an unsigned integer in the radix 690 * specified by the second argument. An unsigned integer maps the 691 * values usually associated with negative numbers to positive 692 * numbers larger than {@code MAX_VALUE}. 693 * 694 * The characters in the string must all be digits of the 695 * specified radix (as determined by whether {@link 696 * java.lang.Character#digit(char, int)} returns a nonnegative 697 * value), except that the first character may be an ASCII plus 698 * sign {@code '+'} ({@code '\u005Cu002B'}). The resulting 699 * integer value is returned. 700 * 701 * <p>An exception of type {@code NumberFormatException} is 702 * thrown if any of the following situations occurs: 703 * <ul> 704 * <li>The first argument is {@code null} or is a string of 705 * length zero. 706 * 707 * <li>The radix is either smaller than 708 * {@link java.lang.Character#MIN_RADIX} or 709 * larger than {@link java.lang.Character#MAX_RADIX}. 710 * 711 * <li>Any character of the string is not a digit of the specified 712 * radix, except that the first character may be a plus sign 713 * {@code '+'} ({@code '\u005Cu002B'}) provided that the 714 * string is longer than length 1. 715 * 716 * <li>The value represented by the string is larger than the 717 * largest unsigned {@code int}, 2<sup>32</sup>-1. 718 * 719 * </ul> 720 * 721 * 722 * @param s the {@code String} containing the unsigned integer 723 * representation to be parsed 724 * @param radix the radix to be used while parsing {@code s}. 725 * @return the integer represented by the string argument in the 726 * specified radix. 727 * @throws NumberFormatException if the {@code String} 728 * does not contain a parsable {@code int}. 729 * @since 1.8 730 */ 731 public static int parseUnsignedInt(String s, int radix) 732 throws NumberFormatException { 733 if (s == null) { 734 throw new NumberFormatException("Cannot parse null string"); 735 } 736 737 if (radix < Character.MIN_RADIX) { 738 throw new NumberFormatException(String.format( 739 "radix %s less than Character.MIN_RADIX", radix)); 740 } 741 742 if (radix > Character.MAX_RADIX) { 743 throw new NumberFormatException(String.format( 744 "radix %s greater than Character.MAX_RADIX", radix)); 745 } 746 747 int len = s.length(); 748 if (len == 0) { 749 throw NumberFormatException.forInputString(s, radix); 750 } 751 int i = 0; 752 char firstChar = s.charAt(i++); 753 if (firstChar == '-') { 754 throw new NumberFormatException(String.format( 755 "Illegal leading minus sign on unsigned string %s.", s)); 756 } 757 int digit = ~0xFF; 758 if (firstChar != '+') { 759 digit = digit(firstChar, radix); 760 } 761 if (digit >= 0 || digit == ~0xFF && len > 1) { 762 int multmax = divideUnsigned(-1, radix); // -1 is max unsigned int 763 int result = digit & 0xFF; 764 boolean inRange = true; 765 while (i < len && (digit = digit(s.charAt(i++), radix)) >= 0 766 && (inRange = compareUnsigned(result, multmax) < 0 767 || result == multmax && digit < -radix * multmax)) { 768 result = radix * result + digit; 769 } 770 if (inRange && i == len && digit >= 0) { 771 return result; 772 } 773 } 774 if (digit < 0) { 775 throw NumberFormatException.forInputString(s, radix); 776 } 777 throw new NumberFormatException(String.format( 778 "String value %s exceeds range of unsigned int.", s)); 779 } 780 781 /** 782 * Parses the {@link CharSequence} argument as an unsigned {@code int} in 783 * the specified {@code radix}, beginning at the specified 784 * {@code beginIndex} and extending to {@code endIndex - 1}. 785 * 786 * <p>The method does not take steps to guard against the 787 * {@code CharSequence} being mutated while parsing. 788 * 789 * @param s the {@code CharSequence} containing the unsigned 790 * {@code int} representation to be parsed 791 * @param beginIndex the beginning index, inclusive. 792 * @param endIndex the ending index, exclusive. 793 * @param radix the radix to be used while parsing {@code s}. 794 * @return the unsigned {@code int} represented by the subsequence in 795 * the specified radix. 796 * @throws NullPointerException if {@code s} is null. 797 * @throws IndexOutOfBoundsException if {@code beginIndex} is 798 * negative, or if {@code beginIndex} is greater than 799 * {@code endIndex} or if {@code endIndex} is greater than 800 * {@code s.length()}. 801 * @throws NumberFormatException if the {@code CharSequence} does not 802 * contain a parsable unsigned {@code int} in the specified 803 * {@code radix}, or if {@code radix} is either smaller than 804 * {@link java.lang.Character#MIN_RADIX} or larger than 805 * {@link java.lang.Character#MAX_RADIX}. 806 * @since 9 807 */ 808 public static int parseUnsignedInt(CharSequence s, int beginIndex, int endIndex, int radix) 809 throws NumberFormatException { 810 Objects.requireNonNull(s); 811 Objects.checkFromToIndex(beginIndex, endIndex, s.length()); 812 813 if (radix < Character.MIN_RADIX) { 814 throw new NumberFormatException(String.format( 815 "radix %s less than Character.MIN_RADIX", radix)); 816 } 817 818 if (radix > Character.MAX_RADIX) { 819 throw new NumberFormatException(String.format( 820 "radix %s greater than Character.MAX_RADIX", radix)); 821 } 822 823 /* 824 * While s can be concurrently modified, it is ensured that each 825 * of its characters is read at most once, from lower to higher indices. 826 * This is obtained by reading them using the pattern s.charAt(i++), 827 * and by not updating i anywhere else. 828 */ 829 if (beginIndex == endIndex) { 830 throw NumberFormatException.forInputString("", radix); 831 } 832 int i = beginIndex; 833 char firstChar = s.charAt(i++); 834 if (firstChar == '-') { 835 throw new NumberFormatException( 836 "Illegal leading minus sign on unsigned string " + s + "."); 837 } 838 int digit = ~0xFF; 839 if (firstChar != '+') { 840 digit = digit(firstChar, radix); 841 } 842 if (digit >= 0 || digit == ~0xFF && endIndex - beginIndex > 1) { 843 int multmax = divideUnsigned(-1, radix); // -1 is max unsigned int 844 int result = digit & 0xFF; 845 boolean inRange = true; 846 while (i < endIndex && (digit = digit(s.charAt(i++), radix)) >= 0 847 && (inRange = compareUnsigned(result, multmax) < 0 848 || result == multmax && digit < -radix * multmax)) { 849 result = radix * result + digit; 850 } 851 if (inRange && i == endIndex && digit >= 0) { 852 return result; 853 } 854 } 855 if (digit < 0) { 856 throw NumberFormatException.forCharSequence(s, beginIndex, 857 endIndex, i - (digit < -1 ? 0 : 1)); 858 } 859 throw new NumberFormatException(String.format( 860 "String value %s exceeds range of unsigned int.", s)); 861 } 862 863 /** 864 * Parses the string argument as an unsigned decimal integer. The 865 * characters in the string must all be decimal digits, except 866 * that the first character may be an ASCII plus sign {@code 867 * '+'} ({@code '\u005Cu002B'}). The resulting integer value 868 * is returned, exactly as if the argument and the radix 10 were 869 * given as arguments to the {@link 870 * #parseUnsignedInt(java.lang.String, int)} method. 871 * 872 * @param s a {@code String} containing the unsigned {@code int} 873 * representation to be parsed 874 * @return the unsigned integer value represented by the argument in decimal. 875 * @throws NumberFormatException if the string does not contain a 876 * parsable unsigned integer. 877 * @since 1.8 878 */ 879 public static int parseUnsignedInt(String s) throws NumberFormatException { 880 return parseUnsignedInt(s, 10); 881 } 882 883 /** 884 * Returns an {@code Integer} object holding the value 885 * extracted from the specified {@code String} when parsed 886 * with the radix given by the second argument. The first argument 887 * is interpreted as representing a signed integer in the radix 888 * specified by the second argument, exactly as if the arguments 889 * were given to the {@link #parseInt(java.lang.String, int)} 890 * method. The result is an {@code Integer} object that 891 * represents the integer value specified by the string. 892 * 893 * <p>In other words, this method returns an {@code Integer} 894 * object equal to the value of: 895 * 896 * <blockquote> 897 * {@code Integer.valueOf(Integer.parseInt(s, radix))} 898 * </blockquote> 899 * 900 * @param s the string to be parsed. 901 * @param radix the radix to be used in interpreting {@code s} 902 * @return an {@code Integer} object holding the value 903 * represented by the string argument in the specified 904 * radix. 905 * @throws NumberFormatException if the {@code String} 906 * does not contain a parsable {@code int}. 907 */ 908 public static Integer valueOf(String s, int radix) throws NumberFormatException { 909 return Integer.valueOf(parseInt(s,radix)); 910 } 911 912 /** 913 * Returns an {@code Integer} object holding the 914 * value of the specified {@code String}. The argument is 915 * interpreted as representing a signed decimal integer, exactly 916 * as if the argument were given to the {@link 917 * #parseInt(java.lang.String)} method. The result is an 918 * {@code Integer} object that represents the integer value 919 * specified by the string. 920 * 921 * <p>In other words, this method returns an {@code Integer} 922 * object equal to the value of: 923 * 924 * <blockquote> 925 * {@code Integer.valueOf(Integer.parseInt(s))} 926 * </blockquote> 927 * 928 * @param s the string to be parsed. 929 * @return an {@code Integer} object holding the value 930 * represented by the string argument. 931 * @throws NumberFormatException if the string cannot be parsed 932 * as an integer. 933 */ 934 public static Integer valueOf(String s) throws NumberFormatException { 935 return Integer.valueOf(parseInt(s, 10)); 936 } 937 938 /** 939 * Cache to support the object identity semantics of autoboxing for values between 940 * -128 and 127 (inclusive) as required by JLS. 941 * 942 * The cache is initialized on first usage. The size of the cache 943 * may be controlled by the {@code -XX:AutoBoxCacheMax=<size>} option. 944 * During VM initialization, java.lang.Integer.IntegerCache.high property 945 * may be set and saved in the private system properties in the 946 * jdk.internal.misc.VM class. 947 * 948 * WARNING: The cache is archived with CDS and reloaded from the shared 949 * archive at runtime. The archived cache (Integer[]) and Integer objects 950 * reside in the closed archive heap regions. Care should be taken when 951 * changing the implementation and the cache array should not be assigned 952 * with new Integer object(s) after initialization. 953 */ 954 955 private static final class IntegerCache { 956 static final int low = -128; 957 static final int high; 958 959 @Stable 960 static final Integer[] cache; 961 static Integer[] archivedCache; 962 963 static { 964 // high value may be configured by property 965 int h = 127; 966 String integerCacheHighPropValue = 967 VM.getSavedProperty("java.lang.Integer.IntegerCache.high"); 968 if (integerCacheHighPropValue != null) { 969 try { 970 h = Math.max(parseInt(integerCacheHighPropValue), 127); 971 // Maximum array size is Integer.MAX_VALUE 972 h = Math.min(h, Integer.MAX_VALUE - (-low) -1); 973 } catch( NumberFormatException nfe) { 974 // If the property cannot be parsed into an int, ignore it. 975 } 976 } 977 high = h; 978 979 // Load IntegerCache.archivedCache from archive, if possible 980 CDS.initializeFromArchive(IntegerCache.class); 981 int size = (high - low) + 1; 982 983 // Use the archived cache if it exists and is large enough 984 if (archivedCache == null || size > archivedCache.length) { 985 Integer[] c = new Integer[size]; 986 int j = low; 987 for(int i = 0; i < c.length; i++) { 988 c[i] = new Integer(j++); 989 } 990 archivedCache = c; 991 } 992 cache = archivedCache; 993 // range [-128, 127] must be interned (JLS7 5.1.7) 994 assert IntegerCache.high >= 127; 995 } 996 997 private IntegerCache() {} 998 } 999 1000 /** 1001 * Returns an {@code Integer} instance representing the specified 1002 * {@code int} value. If a new {@code Integer} instance is not 1003 * required, this method should generally be used in preference to 1004 * the constructor {@link #Integer(int)}, as this method is likely 1005 * to yield significantly better space and time performance by 1006 * caching frequently requested values. 1007 * 1008 * This method will always cache values in the range -128 to 127, 1009 * inclusive, and may cache other values outside of this range. 1010 * 1011 * @param i an {@code int} value. 1012 * @return an {@code Integer} instance representing {@code i}. 1013 * @since 1.5 1014 */ 1015 @IntrinsicCandidate 1016 public static Integer valueOf(int i) { 1017 if (i >= IntegerCache.low && i <= IntegerCache.high) 1018 return IntegerCache.cache[i + (-IntegerCache.low)]; 1019 return new Integer(i); 1020 } 1021 1022 /** 1023 * The value of the {@code Integer}. 1024 * 1025 * @serial 1026 */ 1027 private final int value; 1028 1029 /** 1030 * Constructs a newly allocated {@code Integer} object that 1031 * represents the specified {@code int} value. 1032 * 1033 * @param value the value to be represented by the 1034 * {@code Integer} object. 1035 * 1036 * @deprecated 1037 * It is rarely appropriate to use this constructor. The static factory 1038 * {@link #valueOf(int)} is generally a better choice, as it is 1039 * likely to yield significantly better space and time performance. 1040 */ 1041 @Deprecated(since="9", forRemoval = true) 1042 public Integer(int value) { 1043 this.value = value; 1044 } 1045 1046 /** 1047 * Constructs a newly allocated {@code Integer} object that 1048 * represents the {@code int} value indicated by the 1049 * {@code String} parameter. The string is converted to an 1050 * {@code int} value in exactly the manner used by the 1051 * {@code parseInt} method for radix 10. 1052 * 1053 * @param s the {@code String} to be converted to an {@code Integer}. 1054 * @throws NumberFormatException if the {@code String} does not 1055 * contain a parsable integer. 1056 * 1057 * @deprecated 1058 * It is rarely appropriate to use this constructor. 1059 * Use {@link #parseInt(String)} to convert a string to a 1060 * {@code int} primitive, or use {@link #valueOf(String)} 1061 * to convert a string to an {@code Integer} object. 1062 */ 1063 @Deprecated(since="9", forRemoval = true) 1064 public Integer(String s) throws NumberFormatException { 1065 this.value = parseInt(s, 10); 1066 } 1067 1068 /** 1069 * Returns the value of this {@code Integer} as a {@code byte} 1070 * after a narrowing primitive conversion. 1071 * @jls 5.1.3 Narrowing Primitive Conversion 1072 */ 1073 public byte byteValue() { 1074 return (byte)value; 1075 } 1076 1077 /** 1078 * Returns the value of this {@code Integer} as a {@code short} 1079 * after a narrowing primitive conversion. 1080 * @jls 5.1.3 Narrowing Primitive Conversion 1081 */ 1082 public short shortValue() { 1083 return (short)value; 1084 } 1085 1086 /** 1087 * Returns the value of this {@code Integer} as an 1088 * {@code int}. 1089 */ 1090 @IntrinsicCandidate 1091 public int intValue() { 1092 return value; 1093 } 1094 1095 /** 1096 * Returns the value of this {@code Integer} as a {@code long} 1097 * after a widening primitive conversion. 1098 * @jls 5.1.2 Widening Primitive Conversion 1099 * @see Integer#toUnsignedLong(int) 1100 */ 1101 public long longValue() { 1102 return (long)value; 1103 } 1104 1105 /** 1106 * Returns the value of this {@code Integer} as a {@code float} 1107 * after a widening primitive conversion. 1108 * @jls 5.1.2 Widening Primitive Conversion 1109 */ 1110 public float floatValue() { 1111 return (float)value; 1112 } 1113 1114 /** 1115 * Returns the value of this {@code Integer} as a {@code double} 1116 * after a widening primitive conversion. 1117 * @jls 5.1.2 Widening Primitive Conversion 1118 */ 1119 public double doubleValue() { 1120 return (double)value; 1121 } 1122 1123 /** 1124 * Returns a {@code String} object representing this 1125 * {@code Integer}'s value. The value is converted to signed 1126 * decimal representation and returned as a string, exactly as if 1127 * the integer value were given as an argument to the {@link 1128 * java.lang.Integer#toString(int)} method. 1129 * 1130 * @return a string representation of the value of this object in 1131 * base 10. 1132 */ 1133 public String toString() { 1134 return toString(value); 1135 } 1136 1137 /** 1138 * Returns a hash code for this {@code Integer}. 1139 * 1140 * @return a hash code value for this object, equal to the 1141 * primitive {@code int} value represented by this 1142 * {@code Integer} object. 1143 */ 1144 @Override 1145 public int hashCode() { 1146 return Integer.hashCode(value); 1147 } 1148 1149 /** 1150 * Returns a hash code for an {@code int} value; compatible with 1151 * {@code Integer.hashCode()}. 1152 * 1153 * @param value the value to hash 1154 * @since 1.8 1155 * 1156 * @return a hash code value for an {@code int} value. 1157 */ 1158 public static int hashCode(int value) { 1159 return value; 1160 } 1161 1162 /** 1163 * Compares this object to the specified object. The result is 1164 * {@code true} if and only if the argument is not 1165 * {@code null} and is an {@code Integer} object that 1166 * contains the same {@code int} value as this object. 1167 * 1168 * @param obj the object to compare with. 1169 * @return {@code true} if the objects are the same; 1170 * {@code false} otherwise. 1171 */ 1172 public boolean equals(Object obj) { 1173 if (obj instanceof Integer) { 1174 return value == ((Integer)obj).intValue(); 1175 } 1176 return false; 1177 } 1178 1179 /** 1180 * Determines the integer value of the system property with the 1181 * specified name. 1182 * 1183 * <p>The first argument is treated as the name of a system 1184 * property. System properties are accessible through the {@link 1185 * java.lang.System#getProperty(java.lang.String)} method. The 1186 * string value of this property is then interpreted as an integer 1187 * value using the grammar supported by {@link Integer#decode decode} and 1188 * an {@code Integer} object representing this value is returned. 1189 * 1190 * <p>If there is no property with the specified name, if the 1191 * specified name is empty or {@code null}, or if the property 1192 * does not have the correct numeric format, then {@code null} is 1193 * returned. 1194 * 1195 * <p>In other words, this method returns an {@code Integer} 1196 * object equal to the value of: 1197 * 1198 * <blockquote> 1199 * {@code getInteger(nm, null)} 1200 * </blockquote> 1201 * 1202 * @param nm property name. 1203 * @return the {@code Integer} value of the property. 1204 * @throws SecurityException for the same reasons as 1205 * {@link System#getProperty(String) System.getProperty} 1206 * @see java.lang.System#getProperty(java.lang.String) 1207 * @see java.lang.System#getProperty(java.lang.String, java.lang.String) 1208 */ 1209 public static Integer getInteger(String nm) { 1210 return getInteger(nm, null); 1211 } 1212 1213 /** 1214 * Determines the integer value of the system property with the 1215 * specified name. 1216 * 1217 * <p>The first argument is treated as the name of a system 1218 * property. System properties are accessible through the {@link 1219 * java.lang.System#getProperty(java.lang.String)} method. The 1220 * string value of this property is then interpreted as an integer 1221 * value using the grammar supported by {@link Integer#decode decode} and 1222 * an {@code Integer} object representing this value is returned. 1223 * 1224 * <p>The second argument is the default value. An {@code Integer} object 1225 * that represents the value of the second argument is returned if there 1226 * is no property of the specified name, if the property does not have 1227 * the correct numeric format, or if the specified name is empty or 1228 * {@code null}. 1229 * 1230 * <p>In other words, this method returns an {@code Integer} object 1231 * equal to the value of: 1232 * 1233 * <blockquote> 1234 * {@code getInteger(nm, Integer.valueOf(val))} 1235 * </blockquote> 1236 * 1237 * but in practice it may be implemented in a manner such as: 1238 * 1239 * <blockquote><pre> 1240 * Integer result = getInteger(nm, null); 1241 * return (result == null) ? Integer.valueOf(val) : result; 1242 * </pre></blockquote> 1243 * 1244 * to avoid the unnecessary allocation of an {@code Integer} 1245 * object when the default value is not needed. 1246 * 1247 * @param nm property name. 1248 * @param val default value. 1249 * @return the {@code Integer} value of the property. 1250 * @throws SecurityException for the same reasons as 1251 * {@link System#getProperty(String) System.getProperty} 1252 * @see java.lang.System#getProperty(java.lang.String) 1253 * @see java.lang.System#getProperty(java.lang.String, java.lang.String) 1254 */ 1255 public static Integer getInteger(String nm, int val) { 1256 Integer result = getInteger(nm, null); 1257 return (result == null) ? Integer.valueOf(val) : result; 1258 } 1259 1260 /** 1261 * Returns the integer value of the system property with the 1262 * specified name. The first argument is treated as the name of a 1263 * system property. System properties are accessible through the 1264 * {@link java.lang.System#getProperty(java.lang.String)} method. 1265 * The string value of this property is then interpreted as an 1266 * integer value, as per the {@link Integer#decode decode} method, 1267 * and an {@code Integer} object representing this value is 1268 * returned; in summary: 1269 * 1270 * <ul><li>If the property value begins with the two ASCII characters 1271 * {@code 0x} or the ASCII character {@code #}, not 1272 * followed by a minus sign, then the rest of it is parsed as a 1273 * hexadecimal integer exactly as by the method 1274 * {@link #valueOf(java.lang.String, int)} with radix 16. 1275 * <li>If the property value begins with the ASCII character 1276 * {@code 0} followed by another character, it is parsed as an 1277 * octal integer exactly as by the method 1278 * {@link #valueOf(java.lang.String, int)} with radix 8. 1279 * <li>Otherwise, the property value is parsed as a decimal integer 1280 * exactly as by the method {@link #valueOf(java.lang.String, int)} 1281 * with radix 10. 1282 * </ul> 1283 * 1284 * <p>The second argument is the default value. The default value is 1285 * returned if there is no property of the specified name, if the 1286 * property does not have the correct numeric format, or if the 1287 * specified name is empty or {@code null}. 1288 * 1289 * @param nm property name. 1290 * @param val default value. 1291 * @return the {@code Integer} value of the property. 1292 * @throws SecurityException for the same reasons as 1293 * {@link System#getProperty(String) System.getProperty} 1294 * @see System#getProperty(java.lang.String) 1295 * @see System#getProperty(java.lang.String, java.lang.String) 1296 */ 1297 public static Integer getInteger(String nm, Integer val) { 1298 String v = null; 1299 try { 1300 v = System.getProperty(nm); 1301 } catch (IllegalArgumentException | NullPointerException e) { 1302 } 1303 if (v != null) { 1304 try { 1305 return Integer.decode(v); 1306 } catch (NumberFormatException e) { 1307 } 1308 } 1309 return val; 1310 } 1311 1312 /** 1313 * Decodes a {@code String} into an {@code Integer}. 1314 * Accepts decimal, hexadecimal, and octal numbers given 1315 * by the following grammar: 1316 * 1317 * <blockquote> 1318 * <dl> 1319 * <dt><i>DecodableString:</i> 1320 * <dd><i>Sign<sub>opt</sub> DecimalNumeral</i> 1321 * <dd><i>Sign<sub>opt</sub></i> {@code 0x} <i>HexDigits</i> 1322 * <dd><i>Sign<sub>opt</sub></i> {@code 0X} <i>HexDigits</i> 1323 * <dd><i>Sign<sub>opt</sub></i> {@code #} <i>HexDigits</i> 1324 * <dd><i>Sign<sub>opt</sub></i> {@code 0} <i>OctalDigits</i> 1325 * 1326 * <dt><i>Sign:</i> 1327 * <dd>{@code -} 1328 * <dd>{@code +} 1329 * </dl> 1330 * </blockquote> 1331 * 1332 * <i>DecimalNumeral</i>, <i>HexDigits</i>, and <i>OctalDigits</i> 1333 * are as defined in section {@jls 3.10.1} of 1334 * <cite>The Java Language Specification</cite>, 1335 * except that underscores are not accepted between digits. 1336 * 1337 * <p>The sequence of characters following an optional 1338 * sign and/or radix specifier ("{@code 0x}", "{@code 0X}", 1339 * "{@code #}", or leading zero) is parsed as by the {@code 1340 * Integer.parseInt} method with the indicated radix (10, 16, or 1341 * 8). This sequence of characters must represent a positive 1342 * value or a {@link NumberFormatException} will be thrown. The 1343 * result is negated if first character of the specified {@code 1344 * String} is the minus sign. No whitespace characters are 1345 * permitted in the {@code String}. 1346 * 1347 * @param nm the {@code String} to decode. 1348 * @return an {@code Integer} object holding the {@code int} 1349 * value represented by {@code nm} 1350 * @throws NumberFormatException if the {@code String} does not 1351 * contain a parsable integer. 1352 * @see java.lang.Integer#parseInt(java.lang.String, int) 1353 */ 1354 public static Integer decode(String nm) throws NumberFormatException { 1355 int radix = 10; 1356 int index = 0; 1357 boolean negative = false; 1358 int result; 1359 1360 if (nm.isEmpty()) 1361 throw new NumberFormatException("Zero length string"); 1362 char firstChar = nm.charAt(0); 1363 // Handle sign, if present 1364 if (firstChar == '-') { 1365 negative = true; 1366 index++; 1367 } else if (firstChar == '+') 1368 index++; 1369 1370 // Handle radix specifier, if present 1371 if (nm.startsWith("0x", index) || nm.startsWith("0X", index)) { 1372 index += 2; 1373 radix = 16; 1374 } 1375 else if (nm.startsWith("#", index)) { 1376 index ++; 1377 radix = 16; 1378 } 1379 else if (nm.startsWith("0", index) && nm.length() > 1 + index) { 1380 index ++; 1381 radix = 8; 1382 } 1383 1384 if (nm.startsWith("-", index) || nm.startsWith("+", index)) 1385 throw new NumberFormatException("Sign character in wrong position"); 1386 1387 try { 1388 result = parseInt(nm, index, nm.length(), radix); 1389 result = negative ? -result : result; 1390 } catch (NumberFormatException e) { 1391 // If number is Integer.MIN_VALUE, we'll end up here. The next line 1392 // handles this case, and causes any genuine format error to be 1393 // rethrown. 1394 String constant = negative ? ("-" + nm.substring(index)) 1395 : nm.substring(index); 1396 result = parseInt(constant, radix); 1397 } 1398 return result; 1399 } 1400 1401 /** 1402 * Compares two {@code Integer} objects numerically. 1403 * 1404 * @param anotherInteger the {@code Integer} to be compared. 1405 * @return the value {@code 0} if this {@code Integer} is 1406 * equal to the argument {@code Integer}; a value less than 1407 * {@code 0} if this {@code Integer} is numerically less 1408 * than the argument {@code Integer}; and a value greater 1409 * than {@code 0} if this {@code Integer} is numerically 1410 * greater than the argument {@code Integer} (signed 1411 * comparison). 1412 * @since 1.2 1413 */ 1414 public int compareTo(Integer anotherInteger) { 1415 return compare(this.value, anotherInteger.value); 1416 } 1417 1418 /** 1419 * Compares two {@code int} values numerically. 1420 * The value returned is identical to what would be returned by: 1421 * <pre> 1422 * Integer.valueOf(x).compareTo(Integer.valueOf(y)) 1423 * </pre> 1424 * 1425 * @param x the first {@code int} to compare 1426 * @param y the second {@code int} to compare 1427 * @return the value {@code 0} if {@code x == y}; 1428 * a value less than {@code 0} if {@code x < y}; and 1429 * a value greater than {@code 0} if {@code x > y} 1430 * @since 1.7 1431 */ 1432 public static int compare(int x, int y) { 1433 return (x < y) ? -1 : ((x == y) ? 0 : 1); 1434 } 1435 1436 /** 1437 * Compares two {@code int} values numerically treating the values 1438 * as unsigned. 1439 * 1440 * @param x the first {@code int} to compare 1441 * @param y the second {@code int} to compare 1442 * @return the value {@code 0} if {@code x == y}; a value less 1443 * than {@code 0} if {@code x < y} as unsigned values; and 1444 * a value greater than {@code 0} if {@code x > y} as 1445 * unsigned values 1446 * @since 1.8 1447 */ 1448 @IntrinsicCandidate 1449 public static int compareUnsigned(int x, int y) { 1450 return compare(x + MIN_VALUE, y + MIN_VALUE); 1451 } 1452 1453 /** 1454 * Converts the argument to a {@code long} by an unsigned 1455 * conversion. In an unsigned conversion to a {@code long}, the 1456 * high-order 32 bits of the {@code long} are zero and the 1457 * low-order 32 bits are equal to the bits of the integer 1458 * argument. 1459 * 1460 * Consequently, zero and positive {@code int} values are mapped 1461 * to a numerically equal {@code long} value and negative {@code 1462 * int} values are mapped to a {@code long} value equal to the 1463 * input plus 2<sup>32</sup>. 1464 * 1465 * @param x the value to convert to an unsigned {@code long} 1466 * @return the argument converted to {@code long} by an unsigned 1467 * conversion 1468 * @since 1.8 1469 */ 1470 public static long toUnsignedLong(int x) { 1471 return ((long) x) & 0xffffffffL; 1472 } 1473 1474 /** 1475 * Returns the unsigned quotient of dividing the first argument by 1476 * the second where each argument and the result is interpreted as 1477 * an unsigned value. 1478 * 1479 * <p>Note that in two's complement arithmetic, the three other 1480 * basic arithmetic operations of add, subtract, and multiply are 1481 * bit-wise identical if the two operands are regarded as both 1482 * being signed or both being unsigned. Therefore separate {@code 1483 * addUnsigned}, etc. methods are not provided. 1484 * 1485 * @param dividend the value to be divided 1486 * @param divisor the value doing the dividing 1487 * @return the unsigned quotient of the first argument divided by 1488 * the second argument 1489 * @see #remainderUnsigned 1490 * @since 1.8 1491 */ 1492 @IntrinsicCandidate 1493 public static int divideUnsigned(int dividend, int divisor) { 1494 // In lieu of tricky code, for now just use long arithmetic. 1495 return (int)(toUnsignedLong(dividend) / toUnsignedLong(divisor)); 1496 } 1497 1498 /** 1499 * Returns the unsigned remainder from dividing the first argument 1500 * by the second where each argument and the result is interpreted 1501 * as an unsigned value. 1502 * 1503 * @param dividend the value to be divided 1504 * @param divisor the value doing the dividing 1505 * @return the unsigned remainder of the first argument divided by 1506 * the second argument 1507 * @see #divideUnsigned 1508 * @since 1.8 1509 */ 1510 @IntrinsicCandidate 1511 public static int remainderUnsigned(int dividend, int divisor) { 1512 // In lieu of tricky code, for now just use long arithmetic. 1513 return (int)(toUnsignedLong(dividend) % toUnsignedLong(divisor)); 1514 } 1515 1516 1517 // Bit twiddling 1518 1519 /** 1520 * The number of bits used to represent an {@code int} value in two's 1521 * complement binary form. 1522 * 1523 * @since 1.5 1524 */ 1525 @Native public static final int SIZE = 32; 1526 1527 /** 1528 * The number of bytes used to represent an {@code int} value in two's 1529 * complement binary form. 1530 * 1531 * @since 1.8 1532 */ 1533 public static final int BYTES = SIZE / Byte.SIZE; 1534 1535 /** 1536 * Returns an {@code int} value with at most a single one-bit, in the 1537 * position of the highest-order ("leftmost") one-bit in the specified 1538 * {@code int} value. Returns zero if the specified value has no 1539 * one-bits in its two's complement binary representation, that is, if it 1540 * is equal to zero. 1541 * 1542 * @param i the value whose highest one bit is to be computed 1543 * @return an {@code int} value with a single one-bit, in the position 1544 * of the highest-order one-bit in the specified value, or zero if 1545 * the specified value is itself equal to zero. 1546 * @since 1.5 1547 */ 1548 public static int highestOneBit(int i) { 1549 return i & (MIN_VALUE >>> numberOfLeadingZeros(i)); 1550 } 1551 1552 /** 1553 * Returns an {@code int} value with at most a single one-bit, in the 1554 * position of the lowest-order ("rightmost") one-bit in the specified 1555 * {@code int} value. Returns zero if the specified value has no 1556 * one-bits in its two's complement binary representation, that is, if it 1557 * is equal to zero. 1558 * 1559 * @param i the value whose lowest one bit is to be computed 1560 * @return an {@code int} value with a single one-bit, in the position 1561 * of the lowest-order one-bit in the specified value, or zero if 1562 * the specified value is itself equal to zero. 1563 * @since 1.5 1564 */ 1565 public static int lowestOneBit(int i) { 1566 // HD, Section 2-1 1567 return i & -i; 1568 } 1569 1570 /** 1571 * Returns the number of zero bits preceding the highest-order 1572 * ("leftmost") one-bit in the two's complement binary representation 1573 * of the specified {@code int} value. Returns 32 if the 1574 * specified value has no one-bits in its two's complement representation, 1575 * in other words if it is equal to zero. 1576 * 1577 * <p>Note that this method is closely related to the logarithm base 2. 1578 * For all positive {@code int} values x: 1579 * <ul> 1580 * <li>floor(log<sub>2</sub>(x)) = {@code 31 - numberOfLeadingZeros(x)} 1581 * <li>ceil(log<sub>2</sub>(x)) = {@code 32 - numberOfLeadingZeros(x - 1)} 1582 * </ul> 1583 * 1584 * @param i the value whose number of leading zeros is to be computed 1585 * @return the number of zero bits preceding the highest-order 1586 * ("leftmost") one-bit in the two's complement binary representation 1587 * of the specified {@code int} value, or 32 if the value 1588 * is equal to zero. 1589 * @since 1.5 1590 */ 1591 @IntrinsicCandidate 1592 public static int numberOfLeadingZeros(int i) { 1593 // HD, Count leading 0's 1594 if (i <= 0) 1595 return i == 0 ? 32 : 0; 1596 int n = 31; 1597 if (i >= 1 << 16) { n -= 16; i >>>= 16; } 1598 if (i >= 1 << 8) { n -= 8; i >>>= 8; } 1599 if (i >= 1 << 4) { n -= 4; i >>>= 4; } 1600 if (i >= 1 << 2) { n -= 2; i >>>= 2; } 1601 return n - (i >>> 1); 1602 } 1603 1604 /** 1605 * Returns the number of zero bits following the lowest-order ("rightmost") 1606 * one-bit in the two's complement binary representation of the specified 1607 * {@code int} value. Returns 32 if the specified value has no 1608 * one-bits in its two's complement representation, in other words if it is 1609 * equal to zero. 1610 * 1611 * @param i the value whose number of trailing zeros is to be computed 1612 * @return the number of zero bits following the lowest-order ("rightmost") 1613 * one-bit in the two's complement binary representation of the 1614 * specified {@code int} value, or 32 if the value is equal 1615 * to zero. 1616 * @since 1.5 1617 */ 1618 @IntrinsicCandidate 1619 public static int numberOfTrailingZeros(int i) { 1620 // HD, Count trailing 0's 1621 i = ~i & (i - 1); 1622 if (i <= 0) return i & 32; 1623 int n = 1; 1624 if (i > 1 << 16) { n += 16; i >>>= 16; } 1625 if (i > 1 << 8) { n += 8; i >>>= 8; } 1626 if (i > 1 << 4) { n += 4; i >>>= 4; } 1627 if (i > 1 << 2) { n += 2; i >>>= 2; } 1628 return n + (i >>> 1); 1629 } 1630 1631 /** 1632 * Returns the number of one-bits in the two's complement binary 1633 * representation of the specified {@code int} value. This function is 1634 * sometimes referred to as the <i>population count</i>. 1635 * 1636 * @param i the value whose bits are to be counted 1637 * @return the number of one-bits in the two's complement binary 1638 * representation of the specified {@code int} value. 1639 * @since 1.5 1640 */ 1641 @IntrinsicCandidate 1642 public static int bitCount(int i) { 1643 // HD, Figure 5-2 1644 i = i - ((i >>> 1) & 0x55555555); 1645 i = (i & 0x33333333) + ((i >>> 2) & 0x33333333); 1646 i = (i + (i >>> 4)) & 0x0f0f0f0f; 1647 i = i + (i >>> 8); 1648 i = i + (i >>> 16); 1649 return i & 0x3f; 1650 } 1651 1652 /** 1653 * Returns the value obtained by rotating the two's complement binary 1654 * representation of the specified {@code int} value left by the 1655 * specified number of bits. (Bits shifted out of the left hand, or 1656 * high-order, side reenter on the right, or low-order.) 1657 * 1658 * <p>Note that left rotation with a negative distance is equivalent to 1659 * right rotation: {@code rotateLeft(val, -distance) == rotateRight(val, 1660 * distance)}. Note also that rotation by any multiple of 32 is a 1661 * no-op, so all but the last five bits of the rotation distance can be 1662 * ignored, even if the distance is negative: {@code rotateLeft(val, 1663 * distance) == rotateLeft(val, distance & 0x1F)}. 1664 * 1665 * @param i the value whose bits are to be rotated left 1666 * @param distance the number of bit positions to rotate left 1667 * @return the value obtained by rotating the two's complement binary 1668 * representation of the specified {@code int} value left by the 1669 * specified number of bits. 1670 * @since 1.5 1671 */ 1672 public static int rotateLeft(int i, int distance) { 1673 return (i << distance) | (i >>> -distance); 1674 } 1675 1676 /** 1677 * Returns the value obtained by rotating the two's complement binary 1678 * representation of the specified {@code int} value right by the 1679 * specified number of bits. (Bits shifted out of the right hand, or 1680 * low-order, side reenter on the left, or high-order.) 1681 * 1682 * <p>Note that right rotation with a negative distance is equivalent to 1683 * left rotation: {@code rotateRight(val, -distance) == rotateLeft(val, 1684 * distance)}. Note also that rotation by any multiple of 32 is a 1685 * no-op, so all but the last five bits of the rotation distance can be 1686 * ignored, even if the distance is negative: {@code rotateRight(val, 1687 * distance) == rotateRight(val, distance & 0x1F)}. 1688 * 1689 * @param i the value whose bits are to be rotated right 1690 * @param distance the number of bit positions to rotate right 1691 * @return the value obtained by rotating the two's complement binary 1692 * representation of the specified {@code int} value right by the 1693 * specified number of bits. 1694 * @since 1.5 1695 */ 1696 public static int rotateRight(int i, int distance) { 1697 return (i >>> distance) | (i << -distance); 1698 } 1699 1700 /** 1701 * Returns the value obtained by reversing the order of the bits in the 1702 * two's complement binary representation of the specified {@code int} 1703 * value. 1704 * 1705 * @param i the value to be reversed 1706 * @return the value obtained by reversing order of the bits in the 1707 * specified {@code int} value. 1708 * @since 1.5 1709 */ 1710 @IntrinsicCandidate 1711 public static int reverse(int i) { 1712 // HD, Figure 7-1 1713 i = (i & 0x55555555) << 1 | (i >>> 1) & 0x55555555; 1714 i = (i & 0x33333333) << 2 | (i >>> 2) & 0x33333333; 1715 i = (i & 0x0f0f0f0f) << 4 | (i >>> 4) & 0x0f0f0f0f; 1716 1717 return reverseBytes(i); 1718 } 1719 1720 /** 1721 * Returns the value obtained by compressing the bits of the 1722 * specified {@code int} value, {@code i}, in accordance with 1723 * the specified bit mask. 1724 * <p> 1725 * For each one-bit value {@code mb} of the mask, from least 1726 * significant to most significant, the bit value of {@code i} at 1727 * the same bit location as {@code mb} is assigned to the compressed 1728 * value contiguously starting from the least significant bit location. 1729 * All the upper remaining bits of the compressed value are set 1730 * to zero. 1731 * 1732 * @apiNote 1733 * Consider the simple case of compressing the digits of a hexadecimal 1734 * value: 1735 * {@snippet lang="java" : 1736 * // Compressing drink to food 1737 * compress(0xCAFEBABE, 0xFF00FFF0) == 0xCABAB 1738 * } 1739 * Starting from the least significant hexadecimal digit at position 0 1740 * from the right, the mask {@code 0xFF00FFF0} selects hexadecimal digits 1741 * at positions 1, 2, 3, 6 and 7 of {@code 0xCAFEBABE}. The selected digits 1742 * occur in the resulting compressed value contiguously from digit position 1743 * 0 in the same order. 1744 * <p> 1745 * The following identities all return {@code true} and are helpful to 1746 * understand the behaviour of {@code compress}: 1747 * {@snippet lang="java" : 1748 * // Returns 1 if the bit at position n is one 1749 * compress(x, 1 << n) == (x >> n & 1) 1750 * 1751 * // Logical shift right 1752 * compress(x, -1 << n) == x >>> n 1753 * 1754 * // Any bits not covered by the mask are ignored 1755 * compress(x, m) == compress(x & m, m) 1756 * 1757 * // Compressing a value by itself 1758 * compress(m, m) == (m == -1 || m == 0) ? m : (1 << bitCount(m)) - 1 1759 * 1760 * // Expanding then compressing with the same mask 1761 * compress(expand(x, m), m) == x & compress(m, m) 1762 * } 1763 * <p> 1764 * The Sheep And Goats (SAG) operation (see Hacker's Delight, section 7.7) 1765 * can be implemented as follows: 1766 * {@snippet lang="java" : 1767 * int compressLeft(int i, int mask) { 1768 * // This implementation follows the description in Hacker's Delight which 1769 * // is informative. A more optimal implementation is: 1770 * // Integer.compress(i, mask) << -Integer.bitCount(mask) 1771 * return Integer.reverse( 1772 * Integer.compress(Integer.reverse(i), Integer.reverse(mask))); 1773 * } 1774 * 1775 * int sag(int i, int mask) { 1776 * return compressLeft(i, mask) | Integer.compress(i, ~mask); 1777 * } 1778 * 1779 * // Separate the sheep from the goats 1780 * sag(0xCAFEBABE, 0xFF00FFF0) == 0xCABABFEE 1781 * } 1782 * 1783 * @param i the value whose bits are to be compressed 1784 * @param mask the bit mask 1785 * @return the compressed value 1786 * @see #expand 1787 * @since 19 1788 */ 1789 @IntrinsicCandidate 1790 public static int compress(int i, int mask) { 1791 // See Hacker's Delight (2nd ed) section 7.4 Compress, or Generalized Extract 1792 1793 i = i & mask; // Clear irrelevant bits 1794 int maskCount = ~mask << 1; // Count 0's to right 1795 1796 for (int j = 0; j < 5; j++) { 1797 // Parallel prefix 1798 // Mask prefix identifies bits of the mask that have an odd number of 0's to the right 1799 int maskPrefix = parallelSuffix(maskCount); 1800 // Bits to move 1801 int maskMove = maskPrefix & mask; 1802 // Compress mask 1803 mask = (mask ^ maskMove) | (maskMove >>> (1 << j)); 1804 // Bits of i to be moved 1805 int t = i & maskMove; 1806 // Compress i 1807 i = (i ^ t) | (t >>> (1 << j)); 1808 // Adjust the mask count by identifying bits that have 0 to the right 1809 maskCount = maskCount & ~maskPrefix; 1810 } 1811 return i; 1812 } 1813 1814 /** 1815 * Returns the value obtained by expanding the bits of the 1816 * specified {@code int} value, {@code i}, in accordance with 1817 * the specified bit mask. 1818 * <p> 1819 * For each one-bit value {@code mb} of the mask, from least 1820 * significant to most significant, the next contiguous bit value 1821 * of {@code i} starting at the least significant bit is assigned 1822 * to the expanded value at the same bit location as {@code mb}. 1823 * All other remaining bits of the expanded value are set to zero. 1824 * 1825 * @apiNote 1826 * Consider the simple case of expanding the digits of a hexadecimal 1827 * value: 1828 * {@snippet lang="java" : 1829 * expand(0x0000CABAB, 0xFF00FFF0) == 0xCA00BAB0 1830 * } 1831 * Starting from the least significant hexadecimal digit at position 0 1832 * from the right, the mask {@code 0xFF00FFF0} selects the first five 1833 * hexadecimal digits of {@code 0x0000CABAB}. The selected digits occur 1834 * in the resulting expanded value in order at positions 1, 2, 3, 6, and 7. 1835 * <p> 1836 * The following identities all return {@code true} and are helpful to 1837 * understand the behaviour of {@code expand}: 1838 * {@snippet lang="java" : 1839 * // Logically shift right the bit at position 0 1840 * expand(x, 1 << n) == (x & 1) << n 1841 * 1842 * // Logically shift right 1843 * expand(x, -1 << n) == x << n 1844 * 1845 * // Expanding all bits returns the mask 1846 * expand(-1, m) == m 1847 * 1848 * // Any bits not covered by the mask are ignored 1849 * expand(x, m) == expand(x, m) & m 1850 * 1851 * // Compressing then expanding with the same mask 1852 * expand(compress(x, m), m) == x & m 1853 * } 1854 * <p> 1855 * The select operation for determining the position of the one-bit with 1856 * index {@code n} in a {@code int} value can be implemented as follows: 1857 * {@snippet lang="java" : 1858 * int select(int i, int n) { 1859 * // the one-bit in i (the mask) with index n 1860 * int nthBit = Integer.expand(1 << n, i); 1861 * // the bit position of the one-bit with index n 1862 * return Integer.numberOfTrailingZeros(nthBit); 1863 * } 1864 * 1865 * // The one-bit with index 0 is at bit position 1 1866 * select(0b10101010_10101010, 0) == 1 1867 * // The one-bit with index 3 is at bit position 7 1868 * select(0b10101010_10101010, 3) == 7 1869 * } 1870 * 1871 * @param i the value whose bits are to be expanded 1872 * @param mask the bit mask 1873 * @return the expanded value 1874 * @see #compress 1875 * @since 19 1876 */ 1877 @IntrinsicCandidate 1878 public static int expand(int i, int mask) { 1879 // Save original mask 1880 int originalMask = mask; 1881 // Count 0's to right 1882 int maskCount = ~mask << 1; 1883 int maskPrefix = parallelSuffix(maskCount); 1884 // Bits to move 1885 int maskMove1 = maskPrefix & mask; 1886 // Compress mask 1887 mask = (mask ^ maskMove1) | (maskMove1 >>> (1 << 0)); 1888 maskCount = maskCount & ~maskPrefix; 1889 1890 maskPrefix = parallelSuffix(maskCount); 1891 // Bits to move 1892 int maskMove2 = maskPrefix & mask; 1893 // Compress mask 1894 mask = (mask ^ maskMove2) | (maskMove2 >>> (1 << 1)); 1895 maskCount = maskCount & ~maskPrefix; 1896 1897 maskPrefix = parallelSuffix(maskCount); 1898 // Bits to move 1899 int maskMove3 = maskPrefix & mask; 1900 // Compress mask 1901 mask = (mask ^ maskMove3) | (maskMove3 >>> (1 << 2)); 1902 maskCount = maskCount & ~maskPrefix; 1903 1904 maskPrefix = parallelSuffix(maskCount); 1905 // Bits to move 1906 int maskMove4 = maskPrefix & mask; 1907 // Compress mask 1908 mask = (mask ^ maskMove4) | (maskMove4 >>> (1 << 3)); 1909 maskCount = maskCount & ~maskPrefix; 1910 1911 maskPrefix = parallelSuffix(maskCount); 1912 // Bits to move 1913 int maskMove5 = maskPrefix & mask; 1914 1915 int t = i << (1 << 4); 1916 i = (i & ~maskMove5) | (t & maskMove5); 1917 t = i << (1 << 3); 1918 i = (i & ~maskMove4) | (t & maskMove4); 1919 t = i << (1 << 2); 1920 i = (i & ~maskMove3) | (t & maskMove3); 1921 t = i << (1 << 1); 1922 i = (i & ~maskMove2) | (t & maskMove2); 1923 t = i << (1 << 0); 1924 i = (i & ~maskMove1) | (t & maskMove1); 1925 1926 // Clear irrelevant bits 1927 return i & originalMask; 1928 } 1929 1930 @ForceInline 1931 private static int parallelSuffix(int maskCount) { 1932 int maskPrefix = maskCount ^ (maskCount << 1); 1933 maskPrefix = maskPrefix ^ (maskPrefix << 2); 1934 maskPrefix = maskPrefix ^ (maskPrefix << 4); 1935 maskPrefix = maskPrefix ^ (maskPrefix << 8); 1936 maskPrefix = maskPrefix ^ (maskPrefix << 16); 1937 return maskPrefix; 1938 } 1939 1940 /** 1941 * Returns the signum function of the specified {@code int} value. (The 1942 * return value is -1 if the specified value is negative; 0 if the 1943 * specified value is zero; and 1 if the specified value is positive.) 1944 * 1945 * @param i the value whose signum is to be computed 1946 * @return the signum function of the specified {@code int} value. 1947 * @since 1.5 1948 */ 1949 public static int signum(int i) { 1950 // HD, Section 2-7 1951 return (i >> 31) | (-i >>> 31); 1952 } 1953 1954 /** 1955 * Returns the value obtained by reversing the order of the bytes in the 1956 * two's complement representation of the specified {@code int} value. 1957 * 1958 * @param i the value whose bytes are to be reversed 1959 * @return the value obtained by reversing the bytes in the specified 1960 * {@code int} value. 1961 * @since 1.5 1962 */ 1963 @IntrinsicCandidate 1964 public static int reverseBytes(int i) { 1965 return (i << 24) | 1966 ((i & 0xff00) << 8) | 1967 ((i >>> 8) & 0xff00) | 1968 (i >>> 24); 1969 } 1970 1971 /** 1972 * Adds two integers together as per the + operator. 1973 * 1974 * @param a the first operand 1975 * @param b the second operand 1976 * @return the sum of {@code a} and {@code b} 1977 * @see java.util.function.BinaryOperator 1978 * @since 1.8 1979 */ 1980 public static int sum(int a, int b) { 1981 return a + b; 1982 } 1983 1984 /** 1985 * Returns the greater of two {@code int} values 1986 * as if by calling {@link Math#max(int, int) Math.max}. 1987 * 1988 * @param a the first operand 1989 * @param b the second operand 1990 * @return the greater of {@code a} and {@code b} 1991 * @see java.util.function.BinaryOperator 1992 * @since 1.8 1993 */ 1994 public static int max(int a, int b) { 1995 return Math.max(a, b); 1996 } 1997 1998 /** 1999 * Returns the smaller of two {@code int} values 2000 * as if by calling {@link Math#min(int, int) Math.min}. 2001 * 2002 * @param a the first operand 2003 * @param b the second operand 2004 * @return the smaller of {@code a} and {@code b} 2005 * @see java.util.function.BinaryOperator 2006 * @since 1.8 2007 */ 2008 public static int min(int a, int b) { 2009 return Math.min(a, b); 2010 } 2011 2012 /** 2013 * Returns an {@link Optional} containing the nominal descriptor for this 2014 * instance, which is the instance itself. 2015 * 2016 * @return an {@link Optional} describing the {@linkplain Integer} instance 2017 * @since 12 2018 */ 2019 @Override 2020 public Optional<Integer> describeConstable() { 2021 return Optional.of(this); 2022 } 2023 2024 /** 2025 * Resolves this instance as a {@link ConstantDesc}, the result of which is 2026 * the instance itself. 2027 * 2028 * @param lookup ignored 2029 * @return the {@linkplain Integer} instance 2030 * @since 12 2031 */ 2032 @Override 2033 public Integer resolveConstantDesc(MethodHandles.Lookup lookup) { 2034 return this; 2035 } 2036 2037 /** use serialVersionUID from JDK 1.0.2 for interoperability */ 2038 @java.io.Serial 2039 @Native private static final long serialVersionUID = 1360826667806852920L; 2040 }