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