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