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