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