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