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