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