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