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