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