1 /* 2 * Copyright (c) 1994, 2013, 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 java.lang.annotation.Native; 29 30 /** 31 * The {@code Integer} class wraps a value of the primitive type 32 * {@code int} in an object. An object of type {@code Integer} 33 * contains a single field whose type is {@code int}. 34 * 35 * <p>In addition, this class provides several methods for converting 36 * an {@code int} to a {@code String} and a {@code String} to an 37 * {@code int}, as well as other constants and methods useful when 38 * dealing with an {@code int}. 39 * 40 * <p>Implementation note: The implementations of the "bit twiddling" 41 * methods (such as {@link #highestOneBit(int) highestOneBit} and 42 * {@link #numberOfTrailingZeros(int) numberOfTrailingZeros}) are 43 * based on material from Henry S. Warren, Jr.'s <i>Hacker's 44 * Delight</i>, (Addison Wesley, 2002). 45 * 46 * @author Lee Boynton 47 * @author Arthur van Hoff 48 * @author Josh Bloch 49 * @author Joseph D. Darcy 50 * @since 1.0 51 */ 52 public final class Integer extends Number implements Comparable<Integer> { 53 /** 54 * A constant holding the minimum value an {@code int} can 55 * have, -2<sup>31</sup>. 56 */ 57 @Native public static final int MIN_VALUE = 0x80000000; 58 59 /** 60 * A constant holding the maximum value an {@code int} can 61 * have, 2<sup>31</sup>-1. 62 */ 63 @Native public static final int MAX_VALUE = 0x7fffffff; 64 65 /** 66 * The {@code Class} instance representing the primitive type 67 * {@code int}. 68 * 69 * @since 1.1 70 */ 71 @SuppressWarnings("unchecked") 72 public static final Class<Integer> TYPE = (Class<Integer>) Class.getPrimitiveClass("int"); 73 74 /** 75 * All possible chars for representing a number as a String 76 */ 77 final static char[] digits = { 78 '0' , '1' , '2' , '3' , '4' , '5' , 79 '6' , '7' , '8' , '9' , 'a' , 'b' , 80 'c' , 'd' , 'e' , 'f' , 'g' , 'h' , 81 'i' , 'j' , 'k' , 'l' , 'm' , 'n' , 82 'o' , 'p' , 'q' , 'r' , 's' , 't' , 83 'u' , 'v' , 'w' , 'x' , 'y' , 'z' 84 }; 85 86 /** 87 * Returns a string representation of the first argument in the 88 * radix specified by the second argument. 89 * 90 * <p>If the radix is smaller than {@code Character.MIN_RADIX} 91 * or larger than {@code Character.MAX_RADIX}, then the radix 92 * {@code 10} is used instead. 93 * 94 * <p>If the first argument is negative, the first element of the 95 * result is the ASCII minus character {@code '-'} 96 * ({@code '\u005Cu002D'}). If the first argument is not 97 * negative, no sign character appears in the result. 98 * 99 * <p>The remaining characters of the result represent the magnitude 100 * of the first argument. If the magnitude is zero, it is 101 * represented by a single zero character {@code '0'} 102 * ({@code '\u005Cu0030'}); otherwise, the first character of 103 * the representation of the magnitude will not be the zero 104 * character. The following ASCII characters are used as digits: 105 * 106 * <blockquote> 107 * {@code 0123456789abcdefghijklmnopqrstuvwxyz} 108 * </blockquote> 109 * 110 * These are {@code '\u005Cu0030'} through 111 * {@code '\u005Cu0039'} and {@code '\u005Cu0061'} through 112 * {@code '\u005Cu007A'}. If {@code radix} is 113 * <var>N</var>, then the first <var>N</var> of these characters 114 * are used as radix-<var>N</var> digits in the order shown. Thus, 115 * the digits for hexadecimal (radix 16) are 116 * {@code 0123456789abcdef}. If uppercase letters are 117 * desired, the {@link java.lang.String#toUpperCase()} method may 118 * be called on the result: 119 * 120 * <blockquote> 121 * {@code Integer.toString(n, 16).toUpperCase()} 122 * </blockquote> 123 * 124 * @param i an integer to be converted to a string. 125 * @param radix the radix to use in the string representation. 126 * @return a string representation of the argument in the specified radix. 127 * @see java.lang.Character#MAX_RADIX 128 * @see java.lang.Character#MIN_RADIX 129 */ 130 public static String toString(int i, int radix) { 131 if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX) 132 radix = 10; 133 134 /* Use the faster version */ 135 if (radix == 10) { 136 return toString(i); 137 } 138 139 char buf[] = new char[33]; 140 boolean negative = (i < 0); 141 int charPos = 32; 142 143 if (!negative) { 144 i = -i; 145 } 146 147 while (i <= -radix) { 148 buf[charPos--] = digits[-(i % radix)]; 149 i = i / radix; 150 } 151 buf[charPos] = digits[-i]; 152 153 if (negative) { 154 buf[--charPos] = '-'; 155 } 156 157 return new String(buf, charPos, (33 - charPos)); 158 } 159 160 /** 161 * Returns a string representation of the first argument as an 162 * unsigned integer value in the radix specified by the second 163 * argument. 164 * 165 * <p>If the radix is smaller than {@code Character.MIN_RADIX} 166 * or larger than {@code Character.MAX_RADIX}, then the radix 167 * {@code 10} is used instead. 168 * 169 * <p>Note that since the first argument is treated as an unsigned 170 * value, no leading sign character is printed. 171 * 172 * <p>If the magnitude is zero, it is represented by a single zero 173 * character {@code '0'} ({@code '\u005Cu0030'}); otherwise, 174 * the first character of the representation of the magnitude will 175 * not be the zero character. 176 * 177 * <p>The behavior of radixes and the characters used as digits 178 * are the same as {@link #toString(int, int) toString}. 179 * 180 * @param i an integer to be converted to an unsigned string. 181 * @param radix the radix to use in the string representation. 182 * @return an unsigned string representation of the argument in the specified radix. 183 * @see #toString(int, int) 184 * @since 1.8 185 */ 186 public static String toUnsignedString(int i, int radix) { 187 return Long.toUnsignedString(toUnsignedLong(i), radix); 188 } 189 190 /** 191 * Returns a string representation of the integer argument as an 192 * unsigned integer in base 16. 193 * 194 * <p>The unsigned integer value is the argument plus 2<sup>32</sup> 195 * if the argument is negative; otherwise, it is equal to the 196 * argument. This value is converted to a string of ASCII digits 197 * in hexadecimal (base 16) with no extra leading 198 * {@code 0}s. 199 * 200 * <p>The value of the argument can be recovered from the returned 201 * string {@code s} by calling {@link 202 * Integer#parseUnsignedInt(String, int) 203 * Integer.parseUnsignedInt(s, 16)}. 204 * 205 * <p>If the unsigned magnitude is zero, it is represented by a 206 * single zero character {@code '0'} ({@code '\u005Cu0030'}); 207 * otherwise, the first character of the representation of the 208 * unsigned magnitude will not be the zero character. The 209 * following characters are used as hexadecimal digits: 210 * 211 * <blockquote> 212 * {@code 0123456789abcdef} 213 * </blockquote> 214 * 215 * These are the characters {@code '\u005Cu0030'} through 216 * {@code '\u005Cu0039'} and {@code '\u005Cu0061'} through 217 * {@code '\u005Cu0066'}. If uppercase letters are 218 * desired, the {@link java.lang.String#toUpperCase()} method may 219 * be called on the result: 220 * 221 * <blockquote> 222 * {@code Integer.toHexString(n).toUpperCase()} 223 * </blockquote> 224 * 225 * @param i an integer to be converted to a string. 226 * @return the string representation of the unsigned integer value 227 * represented by the argument in hexadecimal (base 16). 228 * @see #parseUnsignedInt(String, int) 229 * @see #toUnsignedString(int, int) 230 * @see #toHexString(int, int) 231 * @since 1.0.2 232 */ 233 public static String toHexString(int i) { 234 return toUnsignedString0(i, 4); 235 } 236 237 /** 238 * Returns a string representation of the integer argument as an 239 * unsigned integer in base 16, padded with leading zeroes if 240 * necessary. 241 * 242 * <p>The unsigned integer value is the argument plus 2<sup>32</sup> 243 * if the argument is negative; otherwise, it is equal to the 244 * argument. This value is converted to a string of ASCII digits 245 * in hexadecimal (base 16) with possibly appended leading 246 * zeroes. A minimum amount of zeroes is appended to ensure 247 * the length of the resulting string is at least {@code minWidth}. 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 * {@code minWidth} zero characters {@code '0'} ({@code '\u005Cu0030'}). 256 * The following characters are used as hexadecimal digits: 257 * 258 * <blockquote> 259 * {@code 0123456789abcdef} 260 * </blockquote> 261 * 262 * These are the characters {@code '\u005Cu0030'} through 263 * {@code '\u005Cu0039'} and {@code '\u005Cu0061'} through 264 * {@code '\u005Cu0066'}. If uppercase letters are 265 * desired, the {@link java.lang.String#toUpperCase()} method may 266 * be called on the result: 267 * 268 * <blockquote> 269 * {@code Integer.toHexString(n, 6).toUpperCase()} 270 * </blockquote> 271 * 272 * @param i an integer to be converted to a string. 273 * @param minWidth a minimum required length of the resulting string. 274 * @return the string representation of the unsigned integer value 275 * represented by the argument in hexadecimal (base 16), 276 * padded with leading zeroes if necessary. 277 * @see #parseUnsignedInt(String, int) 278 * @see #toUnsignedString(int, int) 279 * @see #toHexString(int) 280 * @since 1.9 281 */ 282 public static String toHexString(int i, int minWidth) { 283 return toUnsignedString0(i, 4, minWidth); 284 } 285 286 287 /** 288 * Returns a string representation of the integer argument as an 289 * unsigned integer in base 8. 290 * 291 * <p>The unsigned integer value is the argument plus 2<sup>32</sup> 292 * if the argument is negative; otherwise, it is equal to the 293 * argument. This value is converted to a string of ASCII digits 294 * in octal (base 8) with no extra leading {@code 0}s. 295 * 296 * <p>The value of the argument can be recovered from the returned 297 * string {@code s} by calling {@link 298 * Integer#parseUnsignedInt(String, int) 299 * Integer.parseUnsignedInt(s, 8)}. 300 * 301 * <p>If the unsigned magnitude is zero, it is represented by a 302 * single zero character {@code '0'} ({@code '\u005Cu0030'}); 303 * otherwise, the first character of the representation of the 304 * unsigned magnitude will not be the zero character. The 305 * following characters are used as octal digits: 306 * 307 * <blockquote> 308 * {@code 01234567} 309 * </blockquote> 310 * 311 * These are the characters {@code '\u005Cu0030'} through 312 * {@code '\u005Cu0037'}. 313 * 314 * @param i an integer to be converted to a string. 315 * @return the string representation of the unsigned integer value 316 * represented by the argument in octal (base 8). 317 * @see #parseUnsignedInt(String, int) 318 * @see #toUnsignedString(int, int) 319 * @since 1.0.2 320 */ 321 public static String toOctalString(int i) { 322 return toUnsignedString0(i, 3); 323 } 324 325 /** 326 * Returns a string representation of the integer argument as an 327 * unsigned integer in base 2. 328 * 329 * <p>The unsigned integer value is the argument plus 2<sup>32</sup> 330 * if the argument is negative; otherwise it is equal to the 331 * argument. This value is converted to a string of ASCII digits 332 * in binary (base 2) with no extra leading {@code 0}s. 333 * 334 * <p>The value of the argument can be recovered from the returned 335 * string {@code s} by calling {@link 336 * Integer#parseUnsignedInt(String, int) 337 * Integer.parseUnsignedInt(s, 2)}. 338 * 339 * <p>If the unsigned magnitude is zero, it is represented by a 340 * single zero character {@code '0'} ({@code '\u005Cu0030'}); 341 * otherwise, the first character of the representation of the 342 * unsigned magnitude will not be the zero character. The 343 * characters {@code '0'} ({@code '\u005Cu0030'}) and {@code 344 * '1'} ({@code '\u005Cu0031'}) are used as binary digits. 345 * 346 * @param i an integer to be converted to a string. 347 * @return the string representation of the unsigned integer value 348 * represented by the argument in binary (base 2). 349 * @see #parseUnsignedInt(String, int) 350 * @see #toUnsignedString(int, int) 351 * @since 1.0.2 352 */ 353 public static String toBinaryString(int i) { 354 return toUnsignedString0(i, 1); 355 } 356 357 /** 358 * Format an integer (treated as unsigned) into a String. 359 * @param val the value to format 360 * @param shift the log2 of the base to format in (4 for hex, 3 for octal, 1 for binary) 361 */ 362 private static String toUnsignedString0(int val, int shift) { 363 // assert shift > 0 && shift <=5 : "Illegal shift value"; 364 int mag = Integer.SIZE - Integer.numberOfLeadingZeros(val); 365 int chars = Math.max(((mag + (shift - 1)) / shift), 1); 366 char[] buf = new char[chars]; 367 368 formatUnsignedInt(val, shift, buf, 0, chars); 369 370 // Use special constructor which takes over "buf". 371 return new String(buf, true); 372 } 373 374 /** 375 * Format an integer (treated as unsigned) into a String. 376 * @param val the value to format 377 * @param shift the log2 of the base to format in (4 for hex, 3 for octal, 1 for binary) 378 * @param minWidth the minimum width of the produced String 379 */ 380 private static String toUnsignedString0(int val, int shift, int minWidth) { 381 // assert shift > 0 && shift <=5 : "Illegal shift value"; 382 int mag = Integer.SIZE - Integer.numberOfLeadingZeros(val); 383 int magLen = (mag + (shift - 1)) / shift; 384 int zeroes = Math.max(Math.max(minWidth, 1) - magLen, 0); 385 char[] buf = new char[magLen + zeroes]; 386 387 for (int i = 0; i < zeroes; ++i) 388 buf[i] = '0'; 389 if (magLen > 0) 390 formatUnsignedInt(val, shift, buf, zeroes, magLen); 391 392 // Use special constructor which takes over "buf". 393 return new String(buf, true); 394 } 395 396 /** 397 * Format an integer (treated as unsigned) into a character buffer. 398 * @param val the unsigned int to format 399 * @param shift the log2 of the base to format in (4 for hex, 3 for octal, 1 for binary) 400 * @param buf the character buffer to write to 401 * @param offset the offset in the destination buffer to start at 402 * @param len the number of characters to write 403 * @return the lowest character location used 404 */ 405 static int formatUnsignedInt(int val, int shift, char[] buf, int offset, int len) { 406 int charPos = len; 407 int radix = 1 << shift; 408 int mask = radix - 1; 409 do { 410 buf[offset + --charPos] = Integer.digits[val & mask]; 411 val >>>= shift; 412 } while (val != 0 && charPos > 0); 413 414 return charPos; 415 } 416 417 final static char [] DigitTens = { 418 '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', 419 '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', 420 '2', '2', '2', '2', '2', '2', '2', '2', '2', '2', 421 '3', '3', '3', '3', '3', '3', '3', '3', '3', '3', 422 '4', '4', '4', '4', '4', '4', '4', '4', '4', '4', 423 '5', '5', '5', '5', '5', '5', '5', '5', '5', '5', 424 '6', '6', '6', '6', '6', '6', '6', '6', '6', '6', 425 '7', '7', '7', '7', '7', '7', '7', '7', '7', '7', 426 '8', '8', '8', '8', '8', '8', '8', '8', '8', '8', 427 '9', '9', '9', '9', '9', '9', '9', '9', '9', '9', 428 } ; 429 430 final static char [] DigitOnes = { 431 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 432 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 433 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 434 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 435 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 436 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 437 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 438 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 439 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 440 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 441 } ; 442 443 // I use the "invariant division by multiplication" trick to 444 // accelerate Integer.toString. In particular we want to 445 // avoid division by 10. 446 // 447 // The "trick" has roughly the same performance characteristics 448 // as the "classic" Integer.toString code on a non-JIT VM. 449 // The trick avoids .rem and .div calls but has a longer code 450 // path and is thus dominated by dispatch overhead. In the 451 // JIT case the dispatch overhead doesn't exist and the 452 // "trick" is considerably faster than the classic code. 453 // 454 // RE: Division by Invariant Integers using Multiplication 455 // T Gralund, P Montgomery 456 // ACM PLDI 1994 457 // 458 459 /** 460 * Returns a {@code String} object representing the 461 * specified integer. The argument is converted to signed decimal 462 * representation and returned as a string, exactly as if the 463 * argument and radix 10 were given as arguments to the {@link 464 * #toString(int, int)} method. 465 * 466 * @param i an integer to be converted. 467 * @return a string representation of the argument in base 10. 468 */ 469 public static String toString(int i) { 470 if (i == Integer.MIN_VALUE) 471 return "-2147483648"; 472 int size = (i < 0) ? stringSize(-i) + 1 : stringSize(i); 473 char[] buf = new char[size]; 474 getChars(i, size, buf); 475 return new String(buf, true); 476 } 477 478 /** 479 * Returns a string representation of the argument as an unsigned 480 * decimal value. 481 * 482 * The argument is converted to unsigned decimal representation 483 * and returned as a string exactly as if the argument and radix 484 * 10 were given as arguments to the {@link #toUnsignedString(int, 485 * int)} method. 486 * 487 * @param i an integer to be converted to an unsigned string. 488 * @return an unsigned string representation of the argument. 489 * @see #toUnsignedString(int, int) 490 * @since 1.8 491 */ 492 public static String toUnsignedString(int i) { 493 return Long.toString(toUnsignedLong(i)); 494 } 495 496 /** 497 * Places characters representing the integer i into the 498 * character array buf. The characters are placed into 499 * the buffer backwards starting with the least significant 500 * digit at the specified index (exclusive), and working 501 * backwards from there. 502 * 503 * Will fail if i == Integer.MIN_VALUE 504 */ 505 static void getChars(int i, int index, char[] buf) { 506 int q, r; 507 int charPos = index; 508 char sign = 0; 509 510 if (i < 0) { 511 sign = '-'; 512 i = -i; 513 } 514 515 // Generate two digits per iteration 516 while (i >= 65536) { 517 q = i / 100; 518 // really: r = i - (q * 100); 519 r = i - ((q << 6) + (q << 5) + (q << 2)); 520 i = q; 521 buf [--charPos] = DigitOnes[r]; 522 buf [--charPos] = DigitTens[r]; 523 } 524 525 // Fall thru to fast mode for smaller numbers 526 // assert(i <= 65536, i); 527 for (;;) { 528 q = (i * 52429) >>> (16+3); 529 r = i - ((q << 3) + (q << 1)); // r = i-(q*10) ... 530 buf [--charPos] = digits [r]; 531 i = q; 532 if (i == 0) break; 533 } 534 if (sign != 0) { 535 buf [--charPos] = sign; 536 } 537 } 538 539 final static int [] sizeTable = { 9, 99, 999, 9999, 99999, 999999, 9999999, 540 99999999, 999999999, Integer.MAX_VALUE }; 541 542 // Requires positive x 543 static int stringSize(int x) { 544 for (int i=0; ; i++) 545 if (x <= sizeTable[i]) 546 return i+1; 547 } 548 549 /** 550 * Parses the string argument as a signed integer in the radix 551 * specified by the second argument. The characters in the string 552 * must all be digits of the specified radix (as determined by 553 * whether {@link java.lang.Character#digit(char, int)} returns a 554 * nonnegative value), except that the first character may be an 555 * ASCII minus sign {@code '-'} ({@code '\u005Cu002D'}) to 556 * indicate a negative value or an ASCII plus sign {@code '+'} 557 * ({@code '\u005Cu002B'}) to indicate a positive value. The 558 * resulting integer value is returned. 559 * 560 * <p>An exception of type {@code NumberFormatException} is 561 * thrown if any of the following situations occurs: 562 * <ul> 563 * <li>The first argument is {@code null} or is a string of 564 * length zero. 565 * 566 * <li>The radix is either smaller than 567 * {@link java.lang.Character#MIN_RADIX} or 568 * larger than {@link java.lang.Character#MAX_RADIX}. 569 * 570 * <li>Any character of the string is not a digit of the specified 571 * radix, except that the first character may be a minus sign 572 * {@code '-'} ({@code '\u005Cu002D'}) or plus sign 573 * {@code '+'} ({@code '\u005Cu002B'}) provided that the 574 * string is longer than length 1. 575 * 576 * <li>The value represented by the string is not a value of type 577 * {@code int}. 578 * </ul> 579 * 580 * <p>Examples: 581 * <blockquote><pre> 582 * parseInt("0", 10) returns 0 583 * parseInt("473", 10) returns 473 584 * parseInt("+42", 10) returns 42 585 * parseInt("-0", 10) returns 0 586 * parseInt("-FF", 16) returns -255 587 * parseInt("1100110", 2) returns 102 588 * parseInt("2147483647", 10) returns 2147483647 589 * parseInt("-2147483648", 10) returns -2147483648 590 * parseInt("2147483648", 10) throws a NumberFormatException 591 * parseInt("99", 8) throws a NumberFormatException 592 * parseInt("Kona", 10) throws a NumberFormatException 593 * parseInt("Kona", 27) returns 411787 594 * </pre></blockquote> 595 * 596 * @param s the {@code String} containing the integer 597 * representation to be parsed 598 * @param radix the radix to be used while parsing {@code s}. 599 * @return the integer represented by the string argument in the 600 * specified radix. 601 * @exception NumberFormatException if the {@code String} 602 * does not contain a parsable {@code int}. 603 */ 604 public static int parseInt(String s, int radix) 605 throws NumberFormatException 606 { 607 /* 608 * WARNING: This method may be invoked early during VM initialization 609 * before IntegerCache is initialized. Care must be taken to not use 610 * the valueOf method. 611 */ 612 613 if (s == null) { 614 throw new NumberFormatException("null"); 615 } 616 617 if (radix < Character.MIN_RADIX) { 618 throw new NumberFormatException("radix " + radix + 619 " less than Character.MIN_RADIX"); 620 } 621 622 if (radix > Character.MAX_RADIX) { 623 throw new NumberFormatException("radix " + radix + 624 " greater than Character.MAX_RADIX"); 625 } 626 627 int result = 0; 628 boolean negative = false; 629 int i = 0, len = s.length(); 630 int limit = -Integer.MAX_VALUE; 631 int multmin; 632 int digit; 633 634 if (len > 0) { 635 char firstChar = s.charAt(0); 636 if (firstChar < '0') { // Possible leading "+" or "-" 637 if (firstChar == '-') { 638 negative = true; 639 limit = Integer.MIN_VALUE; 640 } else if (firstChar != '+') 641 throw NumberFormatException.forInputString(s); 642 643 if (len == 1) // Cannot have lone "+" or "-" 644 throw NumberFormatException.forInputString(s); 645 i++; 646 } 647 multmin = limit / radix; 648 while (i < len) { 649 // Accumulating negatively avoids surprises near MAX_VALUE 650 digit = Character.digit(s.charAt(i++),radix); 651 if (digit < 0) { 652 throw NumberFormatException.forInputString(s); 653 } 654 if (result < multmin) { 655 throw NumberFormatException.forInputString(s); 656 } 657 result *= radix; 658 if (result < limit + digit) { 659 throw NumberFormatException.forInputString(s); 660 } 661 result -= digit; 662 } 663 } else { 664 throw NumberFormatException.forInputString(s); 665 } 666 return negative ? result : -result; 667 } 668 669 /** 670 * Parses the string argument as a signed decimal integer. The 671 * characters in the string must all be decimal digits, except 672 * that the first character may be an ASCII minus sign {@code '-'} 673 * ({@code '\u005Cu002D'}) to indicate a negative value or an 674 * ASCII plus sign {@code '+'} ({@code '\u005Cu002B'}) to 675 * indicate a positive value. The resulting integer value is 676 * returned, exactly as if the argument and the radix 10 were 677 * given as arguments to the {@link #parseInt(java.lang.String, 678 * int)} method. 679 * 680 * @param s a {@code String} containing the {@code int} 681 * representation to be parsed 682 * @return the integer value represented by the argument in decimal. 683 * @exception NumberFormatException if the string does not contain a 684 * parsable integer. 685 */ 686 public static int parseInt(String s) throws NumberFormatException { 687 return parseInt(s,10); 688 } 689 690 /** 691 * Parses the string argument as an unsigned integer in the radix 692 * specified by the second argument. An unsigned integer maps the 693 * values usually associated with negative numbers to positive 694 * numbers larger than {@code MAX_VALUE}. 695 * 696 * The characters in the string must all be digits of the 697 * specified radix (as determined by whether {@link 698 * java.lang.Character#digit(char, int)} returns a nonnegative 699 * value), except that the first character may be an ASCII plus 700 * sign {@code '+'} ({@code '\u005Cu002B'}). The resulting 701 * integer value is returned. 702 * 703 * <p>An exception of type {@code NumberFormatException} is 704 * thrown if any of the following situations occurs: 705 * <ul> 706 * <li>The first argument is {@code null} or is a string of 707 * length zero. 708 * 709 * <li>The radix is either smaller than 710 * {@link java.lang.Character#MIN_RADIX} or 711 * larger than {@link java.lang.Character#MAX_RADIX}. 712 * 713 * <li>Any character of the string is not a digit of the specified 714 * radix, except that the first character may be a plus sign 715 * {@code '+'} ({@code '\u005Cu002B'}) provided that the 716 * string is longer than length 1. 717 * 718 * <li>The value represented by the string is larger than the 719 * largest unsigned {@code int}, 2<sup>32</sup>-1. 720 * 721 * </ul> 722 * 723 * 724 * @param s the {@code String} containing the unsigned 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 * @since 1.8 732 */ 733 public static int parseUnsignedInt(String s, int radix) 734 throws NumberFormatException { 735 if (s == null) { 736 throw new NumberFormatException("null"); 737 } 738 739 int len = s.length(); 740 if (len > 0) { 741 char firstChar = s.charAt(0); 742 if (firstChar == '-') { 743 throw new 744 NumberFormatException(String.format("Illegal leading minus sign " + 745 "on unsigned string %s.", s)); 746 } else { 747 if (len <= 5 || // Integer.MAX_VALUE in Character.MAX_RADIX is 6 digits 748 (radix == 10 && len <= 9) ) { // Integer.MAX_VALUE in base 10 is 10 digits 749 return parseInt(s, radix); 750 } else { 751 long ell = Long.parseLong(s, radix); 752 if ((ell & 0xffff_ffff_0000_0000L) == 0) { 753 return (int) ell; 754 } else { 755 throw new 756 NumberFormatException(String.format("String value %s exceeds " + 757 "range of unsigned int.", s)); 758 } 759 } 760 } 761 } else { 762 throw NumberFormatException.forInputString(s); 763 } 764 } 765 766 /** 767 * Parses the string argument as an unsigned decimal integer. The 768 * characters in the string must all be decimal digits, except 769 * that the first character may be an an ASCII plus sign {@code 770 * '+'} ({@code '\u005Cu002B'}). The resulting integer value 771 * is returned, exactly as if the argument and the radix 10 were 772 * given as arguments to the {@link 773 * #parseUnsignedInt(java.lang.String, int)} method. 774 * 775 * @param s a {@code String} containing the unsigned {@code int} 776 * representation to be parsed 777 * @return the unsigned integer value represented by the argument in decimal. 778 * @throws NumberFormatException if the string does not contain a 779 * parsable unsigned integer. 780 * @since 1.8 781 */ 782 public static int parseUnsignedInt(String s) throws NumberFormatException { 783 return parseUnsignedInt(s, 10); 784 } 785 786 /** 787 * Returns an {@code Integer} object holding the value 788 * extracted from the specified {@code String} when parsed 789 * with the radix given by the second argument. The first argument 790 * is interpreted as representing a signed integer in the radix 791 * specified by the second argument, exactly as if the arguments 792 * were given to the {@link #parseInt(java.lang.String, int)} 793 * method. The result is an {@code Integer} object that 794 * represents the integer value specified by the string. 795 * 796 * <p>In other words, this method returns an {@code Integer} 797 * object equal to the value of: 798 * 799 * <blockquote> 800 * {@code new Integer(Integer.parseInt(s, radix))} 801 * </blockquote> 802 * 803 * @param s the string to be parsed. 804 * @param radix the radix to be used in interpreting {@code s} 805 * @return an {@code Integer} object holding the value 806 * represented by the string argument in the specified 807 * radix. 808 * @exception NumberFormatException if the {@code String} 809 * does not contain a parsable {@code int}. 810 */ 811 public static Integer valueOf(String s, int radix) throws NumberFormatException { 812 return Integer.valueOf(parseInt(s,radix)); 813 } 814 815 /** 816 * Returns an {@code Integer} object holding the 817 * value of the specified {@code String}. The argument is 818 * interpreted as representing a signed decimal integer, exactly 819 * as if the argument were given to the {@link 820 * #parseInt(java.lang.String)} method. The result is an 821 * {@code Integer} object that represents the integer value 822 * specified by the string. 823 * 824 * <p>In other words, this method returns an {@code Integer} 825 * object equal to the value of: 826 * 827 * <blockquote> 828 * {@code new Integer(Integer.parseInt(s))} 829 * </blockquote> 830 * 831 * @param s the string to be parsed. 832 * @return an {@code Integer} object holding the value 833 * represented by the string argument. 834 * @exception NumberFormatException if the string cannot be parsed 835 * as an integer. 836 */ 837 public static Integer valueOf(String s) throws NumberFormatException { 838 return Integer.valueOf(parseInt(s, 10)); 839 } 840 841 /** 842 * Cache to support the object identity semantics of autoboxing for values between 843 * -128 and 127 (inclusive) as required by JLS. 844 * 845 * The cache is initialized on first usage. The size of the cache 846 * may be controlled by the {@code -XX:AutoBoxCacheMax=<size>} option. 847 * During VM initialization, java.lang.Integer.IntegerCache.high property 848 * may be set and saved in the private system properties in the 849 * sun.misc.VM class. 850 */ 851 852 private static class IntegerCache { 853 static final int low = -128; 854 static final int high; 855 static final Integer cache[]; 856 857 static { 858 // high value may be configured by property 859 int h = 127; 860 String integerCacheHighPropValue = 861 sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high"); 862 if (integerCacheHighPropValue != null) { 863 try { 864 int i = parseInt(integerCacheHighPropValue); 865 i = Math.max(i, 127); 866 // Maximum array size is Integer.MAX_VALUE 867 h = Math.min(i, Integer.MAX_VALUE - (-low) -1); 868 } catch( NumberFormatException nfe) { 869 // If the property cannot be parsed into an int, ignore it. 870 } 871 } 872 high = h; 873 874 cache = new Integer[(high - low) + 1]; 875 int j = low; 876 for(int k = 0; k < cache.length; k++) 877 cache[k] = new Integer(j++); 878 879 // range [-128, 127] must be interned (JLS7 5.1.7) 880 assert IntegerCache.high >= 127; 881 } 882 883 private IntegerCache() {} 884 } 885 886 /** 887 * Returns an {@code Integer} instance representing the specified 888 * {@code int} value. If a new {@code Integer} instance is not 889 * required, this method should generally be used in preference to 890 * the constructor {@link #Integer(int)}, as this method is likely 891 * to yield significantly better space and time performance by 892 * caching frequently requested values. 893 * 894 * This method will always cache values in the range -128 to 127, 895 * inclusive, and may cache other values outside of this range. 896 * 897 * @param i an {@code int} value. 898 * @return an {@code Integer} instance representing {@code i}. 899 * @since 1.5 900 */ 901 public static Integer valueOf(int i) { 902 if (i >= IntegerCache.low && i <= IntegerCache.high) 903 return IntegerCache.cache[i + (-IntegerCache.low)]; 904 return new Integer(i); 905 } 906 907 /** 908 * The value of the {@code Integer}. 909 * 910 * @serial 911 */ 912 private final int value; 913 914 /** 915 * Constructs a newly allocated {@code Integer} object that 916 * represents the specified {@code int} value. 917 * 918 * @param value the value to be represented by the 919 * {@code Integer} object. 920 */ 921 public Integer(int value) { 922 this.value = value; 923 } 924 925 /** 926 * Constructs a newly allocated {@code Integer} object that 927 * represents the {@code int} value indicated by the 928 * {@code String} parameter. The string is converted to an 929 * {@code int} value in exactly the manner used by the 930 * {@code parseInt} method for radix 10. 931 * 932 * @param s the {@code String} to be converted to an 933 * {@code Integer}. 934 * @exception NumberFormatException if the {@code String} does not 935 * contain a parsable integer. 936 * @see java.lang.Integer#parseInt(java.lang.String, int) 937 */ 938 public Integer(String s) throws NumberFormatException { 939 this.value = parseInt(s, 10); 940 } 941 942 /** 943 * Returns the value of this {@code Integer} as a {@code byte} 944 * after a narrowing primitive conversion. 945 * @jls 5.1.3 Narrowing Primitive Conversions 946 */ 947 public byte byteValue() { 948 return (byte)value; 949 } 950 951 /** 952 * Returns the value of this {@code Integer} as a {@code short} 953 * after a narrowing primitive conversion. 954 * @jls 5.1.3 Narrowing Primitive Conversions 955 */ 956 public short shortValue() { 957 return (short)value; 958 } 959 960 /** 961 * Returns the value of this {@code Integer} as an 962 * {@code int}. 963 */ 964 public int intValue() { 965 return value; 966 } 967 968 /** 969 * Returns the value of this {@code Integer} as a {@code long} 970 * after a widening primitive conversion. 971 * @jls 5.1.2 Widening Primitive Conversions 972 * @see Integer#toUnsignedLong(int) 973 */ 974 public long longValue() { 975 return (long)value; 976 } 977 978 /** 979 * Returns the value of this {@code Integer} as a {@code float} 980 * after a widening primitive conversion. 981 * @jls 5.1.2 Widening Primitive Conversions 982 */ 983 public float floatValue() { 984 return (float)value; 985 } 986 987 /** 988 * Returns the value of this {@code Integer} as a {@code double} 989 * after a widening primitive conversion. 990 * @jls 5.1.2 Widening Primitive Conversions 991 */ 992 public double doubleValue() { 993 return (double)value; 994 } 995 996 /** 997 * Returns a {@code String} object representing this 998 * {@code Integer}'s value. The value is converted to signed 999 * decimal representation and returned as a string, exactly as if 1000 * the integer value were given as an argument to the {@link 1001 * java.lang.Integer#toString(int)} method. 1002 * 1003 * @return a string representation of the value of this object in 1004 * base 10. 1005 */ 1006 public String toString() { 1007 return toString(value); 1008 } 1009 1010 /** 1011 * Returns a hash code for this {@code Integer}. 1012 * 1013 * @return a hash code value for this object, equal to the 1014 * primitive {@code int} value represented by this 1015 * {@code Integer} object. 1016 */ 1017 @Override 1018 public int hashCode() { 1019 return Integer.hashCode(value); 1020 } 1021 1022 /** 1023 * Returns a hash code for a {@code int} value; compatible with 1024 * {@code Integer.hashCode()}. 1025 * 1026 * @param value the value to hash 1027 * @since 1.8 1028 * 1029 * @return a hash code value for a {@code int} value. 1030 */ 1031 public static int hashCode(int value) { 1032 return value; 1033 } 1034 1035 /** 1036 * Compares this object to the specified object. The result is 1037 * {@code true} if and only if the argument is not 1038 * {@code null} and is an {@code Integer} object that 1039 * contains the same {@code int} value as this object. 1040 * 1041 * @param obj the object to compare with. 1042 * @return {@code true} if the objects are the same; 1043 * {@code false} otherwise. 1044 */ 1045 public boolean equals(Object obj) { 1046 if (obj instanceof Integer) { 1047 return value == ((Integer)obj).intValue(); 1048 } 1049 return false; 1050 } 1051 1052 /** 1053 * Determines the integer value of the system property with the 1054 * specified name. 1055 * 1056 * <p>The first argument is treated as the name of a system 1057 * property. System properties are accessible through the {@link 1058 * java.lang.System#getProperty(java.lang.String)} method. The 1059 * string value of this property is then interpreted as an integer 1060 * value using the grammar supported by {@link Integer#decode decode} and 1061 * an {@code Integer} object representing this value is returned. 1062 * 1063 * <p>If there is no property with the specified name, if the 1064 * specified name is empty or {@code null}, or if the property 1065 * does not have the correct numeric format, then {@code null} is 1066 * returned. 1067 * 1068 * <p>In other words, this method returns an {@code Integer} 1069 * object equal to the value of: 1070 * 1071 * <blockquote> 1072 * {@code getInteger(nm, null)} 1073 * </blockquote> 1074 * 1075 * @param nm property name. 1076 * @return the {@code Integer} value of the property. 1077 * @throws SecurityException for the same reasons as 1078 * {@link System#getProperty(String) System.getProperty} 1079 * @see java.lang.System#getProperty(java.lang.String) 1080 * @see java.lang.System#getProperty(java.lang.String, java.lang.String) 1081 */ 1082 public static Integer getInteger(String nm) { 1083 return getInteger(nm, null); 1084 } 1085 1086 /** 1087 * Determines the integer value of the system property with the 1088 * specified name. 1089 * 1090 * <p>The first argument is treated as the name of a system 1091 * property. System properties are accessible through the {@link 1092 * java.lang.System#getProperty(java.lang.String)} method. The 1093 * string value of this property is then interpreted as an integer 1094 * value using the grammar supported by {@link Integer#decode decode} and 1095 * an {@code Integer} object representing this value is returned. 1096 * 1097 * <p>The second argument is the default value. An {@code Integer} object 1098 * that represents the value of the second argument is returned if there 1099 * is no property of the specified name, if the property does not have 1100 * the correct numeric format, or if the specified name is empty or 1101 * {@code null}. 1102 * 1103 * <p>In other words, this method returns an {@code Integer} object 1104 * equal to the value of: 1105 * 1106 * <blockquote> 1107 * {@code getInteger(nm, new Integer(val))} 1108 * </blockquote> 1109 * 1110 * but in practice it may be implemented in a manner such as: 1111 * 1112 * <blockquote><pre> 1113 * Integer result = getInteger(nm, null); 1114 * return (result == null) ? new Integer(val) : result; 1115 * </pre></blockquote> 1116 * 1117 * to avoid the unnecessary allocation of an {@code Integer} 1118 * object when the default value is not needed. 1119 * 1120 * @param nm property name. 1121 * @param val default value. 1122 * @return the {@code Integer} value of the property. 1123 * @throws SecurityException for the same reasons as 1124 * {@link System#getProperty(String) System.getProperty} 1125 * @see java.lang.System#getProperty(java.lang.String) 1126 * @see java.lang.System#getProperty(java.lang.String, java.lang.String) 1127 */ 1128 public static Integer getInteger(String nm, int val) { 1129 Integer result = getInteger(nm, null); 1130 return (result == null) ? Integer.valueOf(val) : result; 1131 } 1132 1133 /** 1134 * Returns the integer value of the system property with the 1135 * specified name. The first argument is treated as the name of a 1136 * system property. System properties are accessible through the 1137 * {@link java.lang.System#getProperty(java.lang.String)} method. 1138 * The string value of this property is then interpreted as an 1139 * integer value, as per the {@link Integer#decode decode} method, 1140 * and an {@code Integer} object representing this value is 1141 * returned; in summary: 1142 * 1143 * <ul><li>If the property value begins with the two ASCII characters 1144 * {@code 0x} or the ASCII character {@code #}, not 1145 * followed by a minus sign, then the rest of it is parsed as a 1146 * hexadecimal integer exactly as by the method 1147 * {@link #valueOf(java.lang.String, int)} with radix 16. 1148 * <li>If the property value begins with the ASCII character 1149 * {@code 0} followed by another character, it is parsed as an 1150 * octal integer exactly as by the method 1151 * {@link #valueOf(java.lang.String, int)} with radix 8. 1152 * <li>Otherwise, the property value is parsed as a decimal integer 1153 * exactly as by the method {@link #valueOf(java.lang.String, int)} 1154 * with radix 10. 1155 * </ul> 1156 * 1157 * <p>The second argument is the default value. The default value is 1158 * returned if there is no property of the specified name, if the 1159 * property does not have the correct numeric format, or if the 1160 * specified name is empty or {@code null}. 1161 * 1162 * @param nm property name. 1163 * @param val default value. 1164 * @return the {@code Integer} value of the property. 1165 * @throws SecurityException for the same reasons as 1166 * {@link System#getProperty(String) System.getProperty} 1167 * @see System#getProperty(java.lang.String) 1168 * @see System#getProperty(java.lang.String, java.lang.String) 1169 */ 1170 public static Integer getInteger(String nm, Integer val) { 1171 String v = null; 1172 try { 1173 v = System.getProperty(nm); 1174 } catch (IllegalArgumentException | NullPointerException e) { 1175 } 1176 if (v != null) { 1177 try { 1178 return Integer.decode(v); 1179 } catch (NumberFormatException e) { 1180 } 1181 } 1182 return val; 1183 } 1184 1185 /** 1186 * Decodes a {@code String} into an {@code Integer}. 1187 * Accepts decimal, hexadecimal, and octal numbers given 1188 * by the following grammar: 1189 * 1190 * <blockquote> 1191 * <dl> 1192 * <dt><i>DecodableString:</i> 1193 * <dd><i>Sign<sub>opt</sub> DecimalNumeral</i> 1194 * <dd><i>Sign<sub>opt</sub></i> {@code 0x} <i>HexDigits</i> 1195 * <dd><i>Sign<sub>opt</sub></i> {@code 0X} <i>HexDigits</i> 1196 * <dd><i>Sign<sub>opt</sub></i> {@code #} <i>HexDigits</i> 1197 * <dd><i>Sign<sub>opt</sub></i> {@code 0} <i>OctalDigits</i> 1198 * 1199 * <dt><i>Sign:</i> 1200 * <dd>{@code -} 1201 * <dd>{@code +} 1202 * </dl> 1203 * </blockquote> 1204 * 1205 * <i>DecimalNumeral</i>, <i>HexDigits</i>, and <i>OctalDigits</i> 1206 * are as defined in section 3.10.1 of 1207 * <cite>The Java™ Language Specification</cite>, 1208 * except that underscores are not accepted between digits. 1209 * 1210 * <p>The sequence of characters following an optional 1211 * sign and/or radix specifier ("{@code 0x}", "{@code 0X}", 1212 * "{@code #}", or leading zero) is parsed as by the {@code 1213 * Integer.parseInt} method with the indicated radix (10, 16, or 1214 * 8). This sequence of characters must represent a positive 1215 * value or a {@link NumberFormatException} will be thrown. The 1216 * result is negated if first character of the specified {@code 1217 * String} is the minus sign. No whitespace characters are 1218 * permitted in the {@code String}. 1219 * 1220 * @param nm the {@code String} to decode. 1221 * @return an {@code Integer} object holding the {@code int} 1222 * value represented by {@code nm} 1223 * @exception NumberFormatException if the {@code String} does not 1224 * contain a parsable integer. 1225 * @see java.lang.Integer#parseInt(java.lang.String, int) 1226 */ 1227 public static Integer decode(String nm) throws NumberFormatException { 1228 int radix = 10; 1229 int index = 0; 1230 boolean negative = false; 1231 Integer result; 1232 1233 if (nm.length() == 0) 1234 throw new NumberFormatException("Zero length string"); 1235 char firstChar = nm.charAt(0); 1236 // Handle sign, if present 1237 if (firstChar == '-') { 1238 negative = true; 1239 index++; 1240 } else if (firstChar == '+') 1241 index++; 1242 1243 // Handle radix specifier, if present 1244 if (nm.startsWith("0x", index) || nm.startsWith("0X", index)) { 1245 index += 2; 1246 radix = 16; 1247 } 1248 else if (nm.startsWith("#", index)) { 1249 index ++; 1250 radix = 16; 1251 } 1252 else if (nm.startsWith("0", index) && nm.length() > 1 + index) { 1253 index ++; 1254 radix = 8; 1255 } 1256 1257 if (nm.startsWith("-", index) || nm.startsWith("+", index)) 1258 throw new NumberFormatException("Sign character in wrong position"); 1259 1260 try { 1261 result = Integer.valueOf(nm.substring(index), radix); 1262 result = negative ? Integer.valueOf(-result.intValue()) : result; 1263 } catch (NumberFormatException e) { 1264 // If number is Integer.MIN_VALUE, we'll end up here. The next line 1265 // handles this case, and causes any genuine format error to be 1266 // rethrown. 1267 String constant = negative ? ("-" + nm.substring(index)) 1268 : nm.substring(index); 1269 result = Integer.valueOf(constant, radix); 1270 } 1271 return result; 1272 } 1273 1274 /** 1275 * Compares two {@code Integer} objects numerically. 1276 * 1277 * @param anotherInteger the {@code Integer} to be compared. 1278 * @return the value {@code 0} if this {@code Integer} is 1279 * equal to the argument {@code Integer}; a value less than 1280 * {@code 0} if this {@code Integer} is numerically less 1281 * than the argument {@code Integer}; and a value greater 1282 * than {@code 0} if this {@code Integer} is numerically 1283 * greater than the argument {@code Integer} (signed 1284 * comparison). 1285 * @since 1.2 1286 */ 1287 public int compareTo(Integer anotherInteger) { 1288 return compare(this.value, anotherInteger.value); 1289 } 1290 1291 /** 1292 * Compares two {@code int} values numerically. 1293 * The value returned is identical to what would be returned by: 1294 * <pre> 1295 * Integer.valueOf(x).compareTo(Integer.valueOf(y)) 1296 * </pre> 1297 * 1298 * @param x the first {@code int} to compare 1299 * @param y the second {@code int} to compare 1300 * @return the value {@code 0} if {@code x == y}; 1301 * a value less than {@code 0} if {@code x < y}; and 1302 * a value greater than {@code 0} if {@code x > y} 1303 * @since 1.7 1304 */ 1305 public static int compare(int x, int y) { 1306 return (x < y) ? -1 : ((x == y) ? 0 : 1); 1307 } 1308 1309 /** 1310 * Compares two {@code int} values numerically treating the values 1311 * as unsigned. 1312 * 1313 * @param x the first {@code int} to compare 1314 * @param y the second {@code int} to compare 1315 * @return the value {@code 0} if {@code x == y}; a value less 1316 * than {@code 0} if {@code x < y} as unsigned values; and 1317 * a value greater than {@code 0} if {@code x > y} as 1318 * unsigned values 1319 * @since 1.8 1320 */ 1321 public static int compareUnsigned(int x, int y) { 1322 return compare(x + MIN_VALUE, y + MIN_VALUE); 1323 } 1324 1325 /** 1326 * Converts the argument to a {@code long} by an unsigned 1327 * conversion. In an unsigned conversion to a {@code long}, the 1328 * high-order 32 bits of the {@code long} are zero and the 1329 * low-order 32 bits are equal to the bits of the integer 1330 * argument. 1331 * 1332 * Consequently, zero and positive {@code int} values are mapped 1333 * to a numerically equal {@code long} value and negative {@code 1334 * int} values are mapped to a {@code long} value equal to the 1335 * input plus 2<sup>32</sup>. 1336 * 1337 * @param x the value to convert to an unsigned {@code long} 1338 * @return the argument converted to {@code long} by an unsigned 1339 * conversion 1340 * @since 1.8 1341 */ 1342 public static long toUnsignedLong(int x) { 1343 return ((long) x) & 0xffffffffL; 1344 } 1345 1346 /** 1347 * Returns the unsigned quotient of dividing the first argument by 1348 * the second where each argument and the result is interpreted as 1349 * an unsigned value. 1350 * 1351 * <p>Note that in two's complement arithmetic, the three other 1352 * basic arithmetic operations of add, subtract, and multiply are 1353 * bit-wise identical if the two operands are regarded as both 1354 * being signed or both being unsigned. Therefore separate {@code 1355 * addUnsigned}, etc. methods are not provided. 1356 * 1357 * @param dividend the value to be divided 1358 * @param divisor the value doing the dividing 1359 * @return the unsigned quotient of the first argument divided by 1360 * the second argument 1361 * @see #remainderUnsigned 1362 * @since 1.8 1363 */ 1364 public static int divideUnsigned(int dividend, int divisor) { 1365 // In lieu of tricky code, for now just use long arithmetic. 1366 return (int)(toUnsignedLong(dividend) / toUnsignedLong(divisor)); 1367 } 1368 1369 /** 1370 * Returns the unsigned remainder from dividing the first argument 1371 * by the second where each argument and the result is interpreted 1372 * as an unsigned value. 1373 * 1374 * @param dividend the value to be divided 1375 * @param divisor the value doing the dividing 1376 * @return the unsigned remainder of the first argument divided by 1377 * the second argument 1378 * @see #divideUnsigned 1379 * @since 1.8 1380 */ 1381 public static int remainderUnsigned(int dividend, int divisor) { 1382 // In lieu of tricky code, for now just use long arithmetic. 1383 return (int)(toUnsignedLong(dividend) % toUnsignedLong(divisor)); 1384 } 1385 1386 1387 // Bit twiddling 1388 1389 /** 1390 * The number of bits used to represent an {@code int} value in two's 1391 * complement binary form. 1392 * 1393 * @since 1.5 1394 */ 1395 @Native public static final int SIZE = 32; 1396 1397 /** 1398 * The number of bytes used to represent a {@code int} value in two's 1399 * complement binary form. 1400 * 1401 * @since 1.8 1402 */ 1403 public static final int BYTES = SIZE / Byte.SIZE; 1404 1405 /** 1406 * Returns an {@code int} value with at most a single one-bit, in the 1407 * position of the highest-order ("leftmost") one-bit in the specified 1408 * {@code int} value. Returns zero if the specified value has no 1409 * one-bits in its two's complement binary representation, that is, if it 1410 * is equal to zero. 1411 * 1412 * @param i the value whose highest one bit is to be computed 1413 * @return an {@code int} value with a single one-bit, in the position 1414 * of the highest-order one-bit in the specified value, or zero if 1415 * the specified value is itself equal to zero. 1416 * @since 1.5 1417 */ 1418 public static int highestOneBit(int i) { 1419 // HD, Figure 3-1 1420 i |= (i >> 1); 1421 i |= (i >> 2); 1422 i |= (i >> 4); 1423 i |= (i >> 8); 1424 i |= (i >> 16); 1425 return i - (i >>> 1); 1426 } 1427 1428 /** 1429 * Returns an {@code int} value with at most a single one-bit, in the 1430 * position of the lowest-order ("rightmost") one-bit in the specified 1431 * {@code int} value. Returns zero if the specified value has no 1432 * one-bits in its two's complement binary representation, that is, if it 1433 * is equal to zero. 1434 * 1435 * @param i the value whose lowest one bit is to be computed 1436 * @return an {@code int} value with a single one-bit, in the position 1437 * of the lowest-order one-bit in the specified value, or zero if 1438 * the specified value is itself equal to zero. 1439 * @since 1.5 1440 */ 1441 public static int lowestOneBit(int i) { 1442 // HD, Section 2-1 1443 return i & -i; 1444 } 1445 1446 /** 1447 * Returns the number of zero bits preceding the highest-order 1448 * ("leftmost") one-bit in the two's complement binary representation 1449 * of the specified {@code int} value. Returns 32 if the 1450 * specified value has no one-bits in its two's complement representation, 1451 * in other words if it is equal to zero. 1452 * 1453 * <p>Note that this method is closely related to the logarithm base 2. 1454 * For all positive {@code int} values x: 1455 * <ul> 1456 * <li>floor(log<sub>2</sub>(x)) = {@code 31 - numberOfLeadingZeros(x)} 1457 * <li>ceil(log<sub>2</sub>(x)) = {@code 32 - numberOfLeadingZeros(x - 1)} 1458 * </ul> 1459 * 1460 * @param i the value whose number of leading zeros is to be computed 1461 * @return the number of zero bits preceding the highest-order 1462 * ("leftmost") one-bit in the two's complement binary representation 1463 * of the specified {@code int} value, or 32 if the value 1464 * is equal to zero. 1465 * @since 1.5 1466 */ 1467 public static int numberOfLeadingZeros(int i) { 1468 // HD, Figure 5-6 1469 if (i == 0) 1470 return 32; 1471 int n = 1; 1472 if (i >>> 16 == 0) { n += 16; i <<= 16; } 1473 if (i >>> 24 == 0) { n += 8; i <<= 8; } 1474 if (i >>> 28 == 0) { n += 4; i <<= 4; } 1475 if (i >>> 30 == 0) { n += 2; i <<= 2; } 1476 n -= i >>> 31; 1477 return n; 1478 } 1479 1480 /** 1481 * Returns the number of zero bits following the lowest-order ("rightmost") 1482 * one-bit in the two's complement binary representation of the specified 1483 * {@code int} value. Returns 32 if the specified value has no 1484 * one-bits in its two's complement representation, in other words if it is 1485 * equal to zero. 1486 * 1487 * @param i the value whose number of trailing zeros is to be computed 1488 * @return the number of zero bits following the lowest-order ("rightmost") 1489 * one-bit in the two's complement binary representation of the 1490 * specified {@code int} value, or 32 if the value is equal 1491 * to zero. 1492 * @since 1.5 1493 */ 1494 public static int numberOfTrailingZeros(int i) { 1495 // HD, Figure 5-14 1496 int y; 1497 if (i == 0) return 32; 1498 int n = 31; 1499 y = i <<16; if (y != 0) { n = n -16; i = y; } 1500 y = i << 8; if (y != 0) { n = n - 8; i = y; } 1501 y = i << 4; if (y != 0) { n = n - 4; i = y; } 1502 y = i << 2; if (y != 0) { n = n - 2; i = y; } 1503 return n - ((i << 1) >>> 31); 1504 } 1505 1506 /** 1507 * Returns the number of one-bits in the two's complement binary 1508 * representation of the specified {@code int} value. This function is 1509 * sometimes referred to as the <i>population count</i>. 1510 * 1511 * @param i the value whose bits are to be counted 1512 * @return the number of one-bits in the two's complement binary 1513 * representation of the specified {@code int} value. 1514 * @since 1.5 1515 */ 1516 public static int bitCount(int i) { 1517 // HD, Figure 5-2 1518 i = i - ((i >>> 1) & 0x55555555); 1519 i = (i & 0x33333333) + ((i >>> 2) & 0x33333333); 1520 i = (i + (i >>> 4)) & 0x0f0f0f0f; 1521 i = i + (i >>> 8); 1522 i = i + (i >>> 16); 1523 return i & 0x3f; 1524 } 1525 1526 /** 1527 * Returns the value obtained by rotating the two's complement binary 1528 * representation of the specified {@code int} value left by the 1529 * specified number of bits. (Bits shifted out of the left hand, or 1530 * high-order, side reenter on the right, or low-order.) 1531 * 1532 * <p>Note that left rotation with a negative distance is equivalent to 1533 * right rotation: {@code rotateLeft(val, -distance) == rotateRight(val, 1534 * distance)}. Note also that rotation by any multiple of 32 is a 1535 * no-op, so all but the last five bits of the rotation distance can be 1536 * ignored, even if the distance is negative: {@code rotateLeft(val, 1537 * distance) == rotateLeft(val, distance & 0x1F)}. 1538 * 1539 * @param i the value whose bits are to be rotated left 1540 * @param distance the number of bit positions to rotate left 1541 * @return the value obtained by rotating the two's complement binary 1542 * representation of the specified {@code int} value left by the 1543 * specified number of bits. 1544 * @since 1.5 1545 */ 1546 public static int rotateLeft(int i, int distance) { 1547 return (i << distance) | (i >>> -distance); 1548 } 1549 1550 /** 1551 * Returns the value obtained by rotating the two's complement binary 1552 * representation of the specified {@code int} value right by the 1553 * specified number of bits. (Bits shifted out of the right hand, or 1554 * low-order, side reenter on the left, or high-order.) 1555 * 1556 * <p>Note that right rotation with a negative distance is equivalent to 1557 * left rotation: {@code rotateRight(val, -distance) == rotateLeft(val, 1558 * distance)}. Note also that rotation by any multiple of 32 is a 1559 * no-op, so all but the last five bits of the rotation distance can be 1560 * ignored, even if the distance is negative: {@code rotateRight(val, 1561 * distance) == rotateRight(val, distance & 0x1F)}. 1562 * 1563 * @param i the value whose bits are to be rotated right 1564 * @param distance the number of bit positions to rotate right 1565 * @return the value obtained by rotating the two's complement binary 1566 * representation of the specified {@code int} value right by the 1567 * specified number of bits. 1568 * @since 1.5 1569 */ 1570 public static int rotateRight(int i, int distance) { 1571 return (i >>> distance) | (i << -distance); 1572 } 1573 1574 /** 1575 * Returns the value obtained by reversing the order of the bits in the 1576 * two's complement binary representation of the specified {@code int} 1577 * value. 1578 * 1579 * @param i the value to be reversed 1580 * @return the value obtained by reversing order of the bits in the 1581 * specified {@code int} value. 1582 * @since 1.5 1583 */ 1584 public static int reverse(int i) { 1585 // HD, Figure 7-1 1586 i = (i & 0x55555555) << 1 | (i >>> 1) & 0x55555555; 1587 i = (i & 0x33333333) << 2 | (i >>> 2) & 0x33333333; 1588 i = (i & 0x0f0f0f0f) << 4 | (i >>> 4) & 0x0f0f0f0f; 1589 i = (i << 24) | ((i & 0xff00) << 8) | 1590 ((i >>> 8) & 0xff00) | (i >>> 24); 1591 return i; 1592 } 1593 1594 /** 1595 * Returns the signum function of the specified {@code int} value. (The 1596 * return value is -1 if the specified value is negative; 0 if the 1597 * specified value is zero; and 1 if the specified value is positive.) 1598 * 1599 * @param i the value whose signum is to be computed 1600 * @return the signum function of the specified {@code int} value. 1601 * @since 1.5 1602 */ 1603 public static int signum(int i) { 1604 // HD, Section 2-7 1605 return (i >> 31) | (-i >>> 31); 1606 } 1607 1608 /** 1609 * Returns the value obtained by reversing the order of the bytes in the 1610 * two's complement representation of the specified {@code int} value. 1611 * 1612 * @param i the value whose bytes are to be reversed 1613 * @return the value obtained by reversing the bytes in the specified 1614 * {@code int} value. 1615 * @since 1.5 1616 */ 1617 public static int reverseBytes(int i) { 1618 return ((i >>> 24) ) | 1619 ((i >> 8) & 0xFF00) | 1620 ((i << 8) & 0xFF0000) | 1621 ((i << 24)); 1622 } 1623 1624 /** 1625 * Adds two integers together as per the + operator. 1626 * 1627 * @param a the first operand 1628 * @param b the second operand 1629 * @return the sum of {@code a} and {@code b} 1630 * @see java.util.function.BinaryOperator 1631 * @since 1.8 1632 */ 1633 public static int sum(int a, int b) { 1634 return a + b; 1635 } 1636 1637 /** 1638 * Returns the greater of two {@code int} values 1639 * as if by calling {@link Math#max(int, int) Math.max}. 1640 * 1641 * @param a the first operand 1642 * @param b the second operand 1643 * @return the greater of {@code a} and {@code b} 1644 * @see java.util.function.BinaryOperator 1645 * @since 1.8 1646 */ 1647 public static int max(int a, int b) { 1648 return Math.max(a, b); 1649 } 1650 1651 /** 1652 * Returns the smaller of two {@code int} values 1653 * as if by calling {@link Math#min(int, int) Math.min}. 1654 * 1655 * @param a the first operand 1656 * @param b the second operand 1657 * @return the smaller of {@code a} and {@code b} 1658 * @see java.util.function.BinaryOperator 1659 * @since 1.8 1660 */ 1661 public static int min(int a, int b) { 1662 return Math.min(a, b); 1663 } 1664 1665 /** use serialVersionUID from JDK 1.0.2 for interoperability */ 1666 @Native private static final long serialVersionUID = 1360826667806852920L; 1667 }