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