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