Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/classes/java/lang/Integer.java
38829 views
/*1* Copyright (c) 1994, 2013, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425package java.lang;2627import java.lang.annotation.Native;2829/**30* The {@code Integer} class wraps a value of the primitive type31* {@code int} in an object. An object of type {@code Integer}32* contains a single field whose type is {@code int}.33*34* <p>In addition, this class provides several methods for converting35* an {@code int} to a {@code String} and a {@code String} to an36* {@code int}, as well as other constants and methods useful when37* dealing with an {@code int}.38*39* <p>Implementation note: The implementations of the "bit twiddling"40* methods (such as {@link #highestOneBit(int) highestOneBit} and41* {@link #numberOfTrailingZeros(int) numberOfTrailingZeros}) are42* based on material from Henry S. Warren, Jr.'s <i>Hacker's43* Delight</i>, (Addison Wesley, 2002).44*45* @author Lee Boynton46* @author Arthur van Hoff47* @author Josh Bloch48* @author Joseph D. Darcy49* @since JDK1.050*/51public final class Integer extends Number implements Comparable<Integer> {52/**53* A constant holding the minimum value an {@code int} can54* have, -2<sup>31</sup>.55*/56@Native public static final int MIN_VALUE = 0x80000000;5758/**59* A constant holding the maximum value an {@code int} can60* have, 2<sup>31</sup>-1.61*/62@Native public static final int MAX_VALUE = 0x7fffffff;6364/**65* The {@code Class} instance representing the primitive type66* {@code int}.67*68* @since JDK1.169*/70@SuppressWarnings("unchecked")71public static final Class<Integer> TYPE = (Class<Integer>) Class.getPrimitiveClass("int");7273/**74* All possible chars for representing a number as a String75*/76final static char[] digits = {77'0' , '1' , '2' , '3' , '4' , '5' ,78'6' , '7' , '8' , '9' , 'a' , 'b' ,79'c' , 'd' , 'e' , 'f' , 'g' , 'h' ,80'i' , 'j' , 'k' , 'l' , 'm' , 'n' ,81'o' , 'p' , 'q' , 'r' , 's' , 't' ,82'u' , 'v' , 'w' , 'x' , 'y' , 'z'83};8485/**86* Returns a string representation of the first argument in the87* radix specified by the second argument.88*89* <p>If the radix is smaller than {@code Character.MIN_RADIX}90* or larger than {@code Character.MAX_RADIX}, then the radix91* {@code 10} is used instead.92*93* <p>If the first argument is negative, the first element of the94* result is the ASCII minus character {@code '-'}95* ({@code '\u005Cu002D'}). If the first argument is not96* negative, no sign character appears in the result.97*98* <p>The remaining characters of the result represent the magnitude99* of the first argument. If the magnitude is zero, it is100* represented by a single zero character {@code '0'}101* ({@code '\u005Cu0030'}); otherwise, the first character of102* the representation of the magnitude will not be the zero103* character. The following ASCII characters are used as digits:104*105* <blockquote>106* {@code 0123456789abcdefghijklmnopqrstuvwxyz}107* </blockquote>108*109* These are {@code '\u005Cu0030'} through110* {@code '\u005Cu0039'} and {@code '\u005Cu0061'} through111* {@code '\u005Cu007A'}. If {@code radix} is112* <var>N</var>, then the first <var>N</var> of these characters113* are used as radix-<var>N</var> digits in the order shown. Thus,114* the digits for hexadecimal (radix 16) are115* {@code 0123456789abcdef}. If uppercase letters are116* desired, the {@link java.lang.String#toUpperCase()} method may117* be called on the result:118*119* <blockquote>120* {@code Integer.toString(n, 16).toUpperCase()}121* </blockquote>122*123* @param i an integer to be converted to a string.124* @param radix the radix to use in the string representation.125* @return a string representation of the argument in the specified radix.126* @see java.lang.Character#MAX_RADIX127* @see java.lang.Character#MIN_RADIX128*/129public static String toString(int i, int radix) {130if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)131radix = 10;132133/* Use the faster version */134if (radix == 10) {135return toString(i);136}137138char buf[] = new char[33];139boolean negative = (i < 0);140int charPos = 32;141142if (!negative) {143i = -i;144}145146while (i <= -radix) {147buf[charPos--] = digits[-(i % radix)];148i = i / radix;149}150buf[charPos] = digits[-i];151152if (negative) {153buf[--charPos] = '-';154}155156return new String(buf, charPos, (33 - charPos));157}158159/**160* Returns a string representation of the first argument as an161* unsigned integer value in the radix specified by the second162* argument.163*164* <p>If the radix is smaller than {@code Character.MIN_RADIX}165* or larger than {@code Character.MAX_RADIX}, then the radix166* {@code 10} is used instead.167*168* <p>Note that since the first argument is treated as an unsigned169* value, no leading sign character is printed.170*171* <p>If the magnitude is zero, it is represented by a single zero172* character {@code '0'} ({@code '\u005Cu0030'}); otherwise,173* the first character of the representation of the magnitude will174* not be the zero character.175*176* <p>The behavior of radixes and the characters used as digits177* are the same as {@link #toString(int, int) toString}.178*179* @param i an integer to be converted to an unsigned string.180* @param radix the radix to use in the string representation.181* @return an unsigned string representation of the argument in the specified radix.182* @see #toString(int, int)183* @since 1.8184*/185public static String toUnsignedString(int i, int radix) {186return Long.toUnsignedString(toUnsignedLong(i), radix);187}188189/**190* Returns a string representation of the integer argument as an191* unsigned integer in base 16.192*193* <p>The unsigned integer value is the argument plus 2<sup>32</sup>194* if the argument is negative; otherwise, it is equal to the195* argument. This value is converted to a string of ASCII digits196* in hexadecimal (base 16) with no extra leading197* {@code 0}s.198*199* <p>The value of the argument can be recovered from the returned200* string {@code s} by calling {@link201* Integer#parseUnsignedInt(String, int)202* Integer.parseUnsignedInt(s, 16)}.203*204* <p>If the unsigned magnitude is zero, it is represented by a205* single zero character {@code '0'} ({@code '\u005Cu0030'});206* otherwise, the first character of the representation of the207* unsigned magnitude will not be the zero character. The208* following characters are used as hexadecimal digits:209*210* <blockquote>211* {@code 0123456789abcdef}212* </blockquote>213*214* These are the characters {@code '\u005Cu0030'} through215* {@code '\u005Cu0039'} and {@code '\u005Cu0061'} through216* {@code '\u005Cu0066'}. If uppercase letters are217* desired, the {@link java.lang.String#toUpperCase()} method may218* 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 value226* represented by the argument in hexadecimal (base 16).227* @see #parseUnsignedInt(String, int)228* @see #toUnsignedString(int, int)229* @since JDK1.0.2230*/231public static String toHexString(int i) {232return toUnsignedString0(i, 4);233}234235/**236* Returns a string representation of the integer argument as an237* unsigned integer in base 8.238*239* <p>The unsigned integer value is the argument plus 2<sup>32</sup>240* if the argument is negative; otherwise, it is equal to the241* argument. This value is converted to a string of ASCII digits242* in octal (base 8) with no extra leading {@code 0}s.243*244* <p>The value of the argument can be recovered from the returned245* string {@code s} by calling {@link246* Integer#parseUnsignedInt(String, int)247* Integer.parseUnsignedInt(s, 8)}.248*249* <p>If the unsigned magnitude is zero, it is represented by a250* single zero character {@code '0'} ({@code '\u005Cu0030'});251* otherwise, the first character of the representation of the252* unsigned magnitude will not be the zero character. The253* following characters are used as octal digits:254*255* <blockquote>256* {@code 01234567}257* </blockquote>258*259* These are the characters {@code '\u005Cu0030'} through260* {@code '\u005Cu0037'}.261*262* @param i an integer to be converted to a string.263* @return the string representation of the unsigned integer value264* represented by the argument in octal (base 8).265* @see #parseUnsignedInt(String, int)266* @see #toUnsignedString(int, int)267* @since JDK1.0.2268*/269public static String toOctalString(int i) {270return toUnsignedString0(i, 3);271}272273/**274* Returns a string representation of the integer argument as an275* unsigned integer in base 2.276*277* <p>The unsigned integer value is the argument plus 2<sup>32</sup>278* if the argument is negative; otherwise it is equal to the279* argument. This value is converted to a string of ASCII digits280* in binary (base 2) with no extra leading {@code 0}s.281*282* <p>The value of the argument can be recovered from the returned283* string {@code s} by calling {@link284* Integer#parseUnsignedInt(String, int)285* Integer.parseUnsignedInt(s, 2)}.286*287* <p>If the unsigned magnitude is zero, it is represented by a288* single zero character {@code '0'} ({@code '\u005Cu0030'});289* otherwise, the first character of the representation of the290* unsigned magnitude will not be the zero character. The291* characters {@code '0'} ({@code '\u005Cu0030'}) and {@code292* '1'} ({@code '\u005Cu0031'}) 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 value296* represented by the argument in binary (base 2).297* @see #parseUnsignedInt(String, int)298* @see #toUnsignedString(int, int)299* @since JDK1.0.2300*/301public static String toBinaryString(int i) {302return toUnsignedString0(i, 1);303}304305/**306* Convert the integer to an unsigned number.307*/308private static String toUnsignedString0(int val, int shift) {309// assert shift > 0 && shift <=5 : "Illegal shift value";310int mag = Integer.SIZE - Integer.numberOfLeadingZeros(val);311int chars = Math.max(((mag + (shift - 1)) / shift), 1);312char[] buf = new char[chars];313314formatUnsignedInt(val, shift, buf, 0, chars);315316// Use special constructor which takes over "buf".317return new String(buf, true);318}319320/**321* Format a long (treated as unsigned) into a character buffer.322* @param val the unsigned int to format323* @param shift the log2 of the base to format in (4 for hex, 3 for octal, 1 for binary)324* @param buf the character buffer to write to325* @param offset the offset in the destination buffer to start at326* @param len the number of characters to write327* @return the lowest character location used328*/329static int formatUnsignedInt(int val, int shift, char[] buf, int offset, int len) {330int charPos = len;331int radix = 1 << shift;332int mask = radix - 1;333do {334buf[offset + --charPos] = Integer.digits[val & mask];335val >>>= shift;336} while (val != 0 && charPos > 0);337338return charPos;339}340341final static char [] DigitTens = {342'0', '0', '0', '0', '0', '0', '0', '0', '0', '0',343'1', '1', '1', '1', '1', '1', '1', '1', '1', '1',344'2', '2', '2', '2', '2', '2', '2', '2', '2', '2',345'3', '3', '3', '3', '3', '3', '3', '3', '3', '3',346'4', '4', '4', '4', '4', '4', '4', '4', '4', '4',347'5', '5', '5', '5', '5', '5', '5', '5', '5', '5',348'6', '6', '6', '6', '6', '6', '6', '6', '6', '6',349'7', '7', '7', '7', '7', '7', '7', '7', '7', '7',350'8', '8', '8', '8', '8', '8', '8', '8', '8', '8',351'9', '9', '9', '9', '9', '9', '9', '9', '9', '9',352} ;353354final static char [] DigitOnes = {355'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',356'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',357'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',358'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',359'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',360'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',361'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',362'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',363'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',364'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',365} ;366367// I use the "invariant division by multiplication" trick to368// accelerate Integer.toString. In particular we want to369// avoid division by 10.370//371// The "trick" has roughly the same performance characteristics372// as the "classic" Integer.toString code on a non-JIT VM.373// The trick avoids .rem and .div calls but has a longer code374// path and is thus dominated by dispatch overhead. In the375// JIT case the dispatch overhead doesn't exist and the376// "trick" is considerably faster than the classic code.377//378// TODO-FIXME: convert (x * 52429) into the equiv shift-add379// sequence.380//381// RE: Division by Invariant Integers using Multiplication382// T Gralund, P Montgomery383// ACM PLDI 1994384//385386/**387* Returns a {@code String} object representing the388* specified integer. The argument is converted to signed decimal389* representation and returned as a string, exactly as if the390* argument and radix 10 were given as arguments to the {@link391* #toString(int, int)} method.392*393* @param i an integer to be converted.394* @return a string representation of the argument in base 10.395*/396public static String toString(int i) {397if (i == Integer.MIN_VALUE)398return "-2147483648";399int size = (i < 0) ? stringSize(-i) + 1 : stringSize(i);400char[] buf = new char[size];401getChars(i, size, buf);402return new String(buf, true);403}404405/**406* Returns a string representation of the argument as an unsigned407* decimal value.408*409* The argument is converted to unsigned decimal representation410* and returned as a string exactly as if the argument and radix411* 10 were given as arguments to the {@link #toUnsignedString(int,412* int)} method.413*414* @param i an integer to be converted to an unsigned string.415* @return an unsigned string representation of the argument.416* @see #toUnsignedString(int, int)417* @since 1.8418*/419public static String toUnsignedString(int i) {420return Long.toString(toUnsignedLong(i));421}422423/**424* Places characters representing the integer i into the425* character array buf. The characters are placed into426* the buffer backwards starting with the least significant427* digit at the specified index (exclusive), and working428* backwards from there.429*430* Will fail if i == Integer.MIN_VALUE431*/432static void getChars(int i, int index, char[] buf) {433int q, r;434int charPos = index;435char sign = 0;436437if (i < 0) {438sign = '-';439i = -i;440}441442// Generate two digits per iteration443while (i >= 65536) {444q = i / 100;445// really: r = i - (q * 100);446r = i - ((q << 6) + (q << 5) + (q << 2));447i = q;448buf [--charPos] = DigitOnes[r];449buf [--charPos] = DigitTens[r];450}451452// Fall thru to fast mode for smaller numbers453// assert(i <= 65536, i);454for (;;) {455q = (i * 52429) >>> (16+3);456r = i - ((q << 3) + (q << 1)); // r = i-(q*10) ...457buf [--charPos] = digits [r];458i = q;459if (i == 0) break;460}461if (sign != 0) {462buf [--charPos] = sign;463}464}465466final static int [] sizeTable = { 9, 99, 999, 9999, 99999, 999999, 9999999,46799999999, 999999999, Integer.MAX_VALUE };468469// Requires positive x470static int stringSize(int x) {471for (int i=0; ; i++)472if (x <= sizeTable[i])473return i+1;474}475476/**477* Parses the string argument as a signed integer in the radix478* specified by the second argument. The characters in the string479* must all be digits of the specified radix (as determined by480* whether {@link java.lang.Character#digit(char, int)} returns a481* nonnegative value), except that the first character may be an482* ASCII minus sign {@code '-'} ({@code '\u005Cu002D'}) to483* indicate a negative value or an ASCII plus sign {@code '+'}484* ({@code '\u005Cu002B'}) to indicate a positive value. The485* resulting integer value is returned.486*487* <p>An exception of type {@code NumberFormatException} is488* thrown if any of the following situations occurs:489* <ul>490* <li>The first argument is {@code null} or is a string of491* length zero.492*493* <li>The radix is either smaller than494* {@link java.lang.Character#MIN_RADIX} or495* larger than {@link java.lang.Character#MAX_RADIX}.496*497* <li>Any character of the string is not a digit of the specified498* radix, except that the first character may be a minus sign499* {@code '-'} ({@code '\u005Cu002D'}) or plus sign500* {@code '+'} ({@code '\u005Cu002B'}) provided that the501* string is longer than length 1.502*503* <li>The value represented by the string is not a value of type504* {@code int}.505* </ul>506*507* <p>Examples:508* <blockquote><pre>509* parseInt("0", 10) returns 0510* parseInt("473", 10) returns 473511* parseInt("+42", 10) returns 42512* parseInt("-0", 10) returns 0513* parseInt("-FF", 16) returns -255514* parseInt("1100110", 2) returns 102515* parseInt("2147483647", 10) returns 2147483647516* parseInt("-2147483648", 10) returns -2147483648517* parseInt("2147483648", 10) throws a NumberFormatException518* parseInt("99", 8) throws a NumberFormatException519* parseInt("Kona", 10) throws a NumberFormatException520* parseInt("Kona", 27) returns 411787521* </pre></blockquote>522*523* @param s the {@code String} containing the integer524* representation to be parsed525* @param radix the radix to be used while parsing {@code s}.526* @return the integer represented by the string argument in the527* specified radix.528* @exception NumberFormatException if the {@code String}529* does not contain a parsable {@code int}.530*/531public static int parseInt(String s, int radix)532throws NumberFormatException533{534/*535* WARNING: This method may be invoked early during VM initialization536* before IntegerCache is initialized. Care must be taken to not use537* the valueOf method.538*/539540if (s == null) {541throw new NumberFormatException("null");542}543544if (radix < Character.MIN_RADIX) {545throw new NumberFormatException("radix " + radix +546" less than Character.MIN_RADIX");547}548549if (radix > Character.MAX_RADIX) {550throw new NumberFormatException("radix " + radix +551" greater than Character.MAX_RADIX");552}553554int result = 0;555boolean negative = false;556int i = 0, len = s.length();557int limit = -Integer.MAX_VALUE;558int multmin;559int digit;560561if (len > 0) {562char firstChar = s.charAt(0);563if (firstChar < '0') { // Possible leading "+" or "-"564if (firstChar == '-') {565negative = true;566limit = Integer.MIN_VALUE;567} else if (firstChar != '+')568throw NumberFormatException.forInputString(s);569570if (len == 1) // Cannot have lone "+" or "-"571throw NumberFormatException.forInputString(s);572i++;573}574multmin = limit / radix;575while (i < len) {576// Accumulating negatively avoids surprises near MAX_VALUE577digit = Character.digit(s.charAt(i++),radix);578if (digit < 0) {579throw NumberFormatException.forInputString(s);580}581if (result < multmin) {582throw NumberFormatException.forInputString(s);583}584result *= radix;585if (result < limit + digit) {586throw NumberFormatException.forInputString(s);587}588result -= digit;589}590} else {591throw NumberFormatException.forInputString(s);592}593return negative ? result : -result;594}595596/**597* Parses the string argument as a signed decimal integer. The598* characters in the string must all be decimal digits, except599* that the first character may be an ASCII minus sign {@code '-'}600* ({@code '\u005Cu002D'}) to indicate a negative value or an601* ASCII plus sign {@code '+'} ({@code '\u005Cu002B'}) to602* indicate a positive value. The resulting integer value is603* returned, exactly as if the argument and the radix 10 were604* given as arguments to the {@link #parseInt(java.lang.String,605* int)} method.606*607* @param s a {@code String} containing the {@code int}608* representation to be parsed609* @return the integer value represented by the argument in decimal.610* @exception NumberFormatException if the string does not contain a611* parsable integer.612*/613public static int parseInt(String s) throws NumberFormatException {614return parseInt(s,10);615}616617/**618* Parses the string argument as an unsigned integer in the radix619* specified by the second argument. An unsigned integer maps the620* values usually associated with negative numbers to positive621* numbers larger than {@code MAX_VALUE}.622*623* The characters in the string must all be digits of the624* specified radix (as determined by whether {@link625* java.lang.Character#digit(char, int)} returns a nonnegative626* value), except that the first character may be an ASCII plus627* sign {@code '+'} ({@code '\u005Cu002B'}). The resulting628* integer value is returned.629*630* <p>An exception of type {@code NumberFormatException} is631* thrown if any of the following situations occurs:632* <ul>633* <li>The first argument is {@code null} or is a string of634* length zero.635*636* <li>The radix is either smaller than637* {@link java.lang.Character#MIN_RADIX} or638* larger than {@link java.lang.Character#MAX_RADIX}.639*640* <li>Any character of the string is not a digit of the specified641* radix, except that the first character may be a plus sign642* {@code '+'} ({@code '\u005Cu002B'}) provided that the643* string is longer than length 1.644*645* <li>The value represented by the string is larger than the646* largest unsigned {@code int}, 2<sup>32</sup>-1.647*648* </ul>649*650*651* @param s the {@code String} containing the unsigned integer652* representation to be parsed653* @param radix the radix to be used while parsing {@code s}.654* @return the integer represented by the string argument in the655* specified radix.656* @throws NumberFormatException if the {@code String}657* does not contain a parsable {@code int}.658* @since 1.8659*/660public static int parseUnsignedInt(String s, int radix)661throws NumberFormatException {662if (s == null) {663throw new NumberFormatException("null");664}665666int len = s.length();667if (len > 0) {668char firstChar = s.charAt(0);669if (firstChar == '-') {670throw new671NumberFormatException(String.format("Illegal leading minus sign " +672"on unsigned string %s.", s));673} else {674if (len <= 5 || // Integer.MAX_VALUE in Character.MAX_RADIX is 6 digits675(radix == 10 && len <= 9) ) { // Integer.MAX_VALUE in base 10 is 10 digits676return parseInt(s, radix);677} else {678long ell = Long.parseLong(s, radix);679if ((ell & 0xffff_ffff_0000_0000L) == 0) {680return (int) ell;681} else {682throw new683NumberFormatException(String.format("String value %s exceeds " +684"range of unsigned int.", s));685}686}687}688} else {689throw NumberFormatException.forInputString(s);690}691}692693/**694* Parses the string argument as an unsigned decimal integer. The695* characters in the string must all be decimal digits, except696* that the first character may be an an ASCII plus sign {@code697* '+'} ({@code '\u005Cu002B'}). The resulting integer value698* is returned, exactly as if the argument and the radix 10 were699* given as arguments to the {@link700* #parseUnsignedInt(java.lang.String, int)} method.701*702* @param s a {@code String} containing the unsigned {@code int}703* representation to be parsed704* @return the unsigned integer value represented by the argument in decimal.705* @throws NumberFormatException if the string does not contain a706* parsable unsigned integer.707* @since 1.8708*/709public static int parseUnsignedInt(String s) throws NumberFormatException {710return parseUnsignedInt(s, 10);711}712713/**714* Returns an {@code Integer} object holding the value715* extracted from the specified {@code String} when parsed716* with the radix given by the second argument. The first argument717* is interpreted as representing a signed integer in the radix718* specified by the second argument, exactly as if the arguments719* were given to the {@link #parseInt(java.lang.String, int)}720* method. The result is an {@code Integer} object that721* represents the integer value specified by the string.722*723* <p>In other words, this method returns an {@code Integer}724* object equal to the value of:725*726* <blockquote>727* {@code new Integer(Integer.parseInt(s, radix))}728* </blockquote>729*730* @param s the string to be parsed.731* @param radix the radix to be used in interpreting {@code s}732* @return an {@code Integer} object holding the value733* represented by the string argument in the specified734* radix.735* @exception NumberFormatException if the {@code String}736* does not contain a parsable {@code int}.737*/738public static Integer valueOf(String s, int radix) throws NumberFormatException {739return Integer.valueOf(parseInt(s,radix));740}741742/**743* Returns an {@code Integer} object holding the744* value of the specified {@code String}. The argument is745* interpreted as representing a signed decimal integer, exactly746* as if the argument were given to the {@link747* #parseInt(java.lang.String)} method. The result is an748* {@code Integer} object that represents the integer value749* specified by the string.750*751* <p>In other words, this method returns an {@code Integer}752* object equal to the value of:753*754* <blockquote>755* {@code new Integer(Integer.parseInt(s))}756* </blockquote>757*758* @param s the string to be parsed.759* @return an {@code Integer} object holding the value760* represented by the string argument.761* @exception NumberFormatException if the string cannot be parsed762* as an integer.763*/764public static Integer valueOf(String s) throws NumberFormatException {765return Integer.valueOf(parseInt(s, 10));766}767768/**769* Cache to support the object identity semantics of autoboxing for values between770* -128 and 127 (inclusive) as required by JLS.771*772* The cache is initialized on first usage. The size of the cache773* may be controlled by the {@code -XX:AutoBoxCacheMax=<size>} option.774* During VM initialization, java.lang.Integer.IntegerCache.high property775* may be set and saved in the private system properties in the776* sun.misc.VM class.777*/778779private static class IntegerCache {780static final int low = -128;781static final int high;782static final Integer cache[];783784static {785// high value may be configured by property786int h = 127;787String integerCacheHighPropValue =788sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");789if (integerCacheHighPropValue != null) {790try {791int i = parseInt(integerCacheHighPropValue);792i = Math.max(i, 127);793// Maximum array size is Integer.MAX_VALUE794h = Math.min(i, Integer.MAX_VALUE - (-low) -1);795} catch( NumberFormatException nfe) {796// If the property cannot be parsed into an int, ignore it.797}798}799high = h;800801cache = new Integer[(high - low) + 1];802int j = low;803for(int k = 0; k < cache.length; k++)804cache[k] = new Integer(j++);805806// range [-128, 127] must be interned (JLS7 5.1.7)807assert IntegerCache.high >= 127;808}809810private IntegerCache() {}811}812813/**814* Returns an {@code Integer} instance representing the specified815* {@code int} value. If a new {@code Integer} instance is not816* required, this method should generally be used in preference to817* the constructor {@link #Integer(int)}, as this method is likely818* to yield significantly better space and time performance by819* caching frequently requested values.820*821* This method will always cache values in the range -128 to 127,822* inclusive, and may cache other values outside of this range.823*824* @param i an {@code int} value.825* @return an {@code Integer} instance representing {@code i}.826* @since 1.5827*/828public static Integer valueOf(int i) {829if (i >= IntegerCache.low && i <= IntegerCache.high)830return IntegerCache.cache[i + (-IntegerCache.low)];831return new Integer(i);832}833834/**835* The value of the {@code Integer}.836*837* @serial838*/839private final int value;840841/**842* Constructs a newly allocated {@code Integer} object that843* represents the specified {@code int} value.844*845* @param value the value to be represented by the846* {@code Integer} object.847*/848public Integer(int value) {849this.value = value;850}851852/**853* Constructs a newly allocated {@code Integer} object that854* represents the {@code int} value indicated by the855* {@code String} parameter. The string is converted to an856* {@code int} value in exactly the manner used by the857* {@code parseInt} method for radix 10.858*859* @param s the {@code String} to be converted to an860* {@code Integer}.861* @exception NumberFormatException if the {@code String} does not862* contain a parsable integer.863* @see java.lang.Integer#parseInt(java.lang.String, int)864*/865public Integer(String s) throws NumberFormatException {866this.value = parseInt(s, 10);867}868869/**870* Returns the value of this {@code Integer} as a {@code byte}871* after a narrowing primitive conversion.872* @jls 5.1.3 Narrowing Primitive Conversions873*/874public byte byteValue() {875return (byte)value;876}877878/**879* Returns the value of this {@code Integer} as a {@code short}880* after a narrowing primitive conversion.881* @jls 5.1.3 Narrowing Primitive Conversions882*/883public short shortValue() {884return (short)value;885}886887/**888* Returns the value of this {@code Integer} as an889* {@code int}.890*/891public int intValue() {892return value;893}894895/**896* Returns the value of this {@code Integer} as a {@code long}897* after a widening primitive conversion.898* @jls 5.1.2 Widening Primitive Conversions899* @see Integer#toUnsignedLong(int)900*/901public long longValue() {902return (long)value;903}904905/**906* Returns the value of this {@code Integer} as a {@code float}907* after a widening primitive conversion.908* @jls 5.1.2 Widening Primitive Conversions909*/910public float floatValue() {911return (float)value;912}913914/**915* Returns the value of this {@code Integer} as a {@code double}916* after a widening primitive conversion.917* @jls 5.1.2 Widening Primitive Conversions918*/919public double doubleValue() {920return (double)value;921}922923/**924* Returns a {@code String} object representing this925* {@code Integer}'s value. The value is converted to signed926* decimal representation and returned as a string, exactly as if927* the integer value were given as an argument to the {@link928* java.lang.Integer#toString(int)} method.929*930* @return a string representation of the value of this object in931* base 10.932*/933public String toString() {934return toString(value);935}936937/**938* Returns a hash code for this {@code Integer}.939*940* @return a hash code value for this object, equal to the941* primitive {@code int} value represented by this942* {@code Integer} object.943*/944@Override945public int hashCode() {946return Integer.hashCode(value);947}948949/**950* Returns a hash code for a {@code int} value; compatible with951* {@code Integer.hashCode()}.952*953* @param value the value to hash954* @since 1.8955*956* @return a hash code value for a {@code int} value.957*/958public static int hashCode(int value) {959return value;960}961962/**963* Compares this object to the specified object. The result is964* {@code true} if and only if the argument is not965* {@code null} and is an {@code Integer} object that966* contains the same {@code int} value as this object.967*968* @param obj the object to compare with.969* @return {@code true} if the objects are the same;970* {@code false} otherwise.971*/972public boolean equals(Object obj) {973if (obj instanceof Integer) {974return value == ((Integer)obj).intValue();975}976return false;977}978979/**980* Determines the integer value of the system property with the981* specified name.982*983* <p>The first argument is treated as the name of a system984* property. System properties are accessible through the {@link985* java.lang.System#getProperty(java.lang.String)} method. The986* string value of this property is then interpreted as an integer987* value using the grammar supported by {@link Integer#decode decode} and988* an {@code Integer} object representing this value is returned.989*990* <p>If there is no property with the specified name, if the991* specified name is empty or {@code null}, or if the property992* does not have the correct numeric format, then {@code null} is993* returned.994*995* <p>In other words, this method returns an {@code Integer}996* object equal to the value of:997*998* <blockquote>999* {@code getInteger(nm, null)}1000* </blockquote>1001*1002* @param nm property name.1003* @return the {@code Integer} value of the property.1004* @throws SecurityException for the same reasons as1005* {@link System#getProperty(String) System.getProperty}1006* @see java.lang.System#getProperty(java.lang.String)1007* @see java.lang.System#getProperty(java.lang.String, java.lang.String)1008*/1009public static Integer getInteger(String nm) {1010return getInteger(nm, null);1011}10121013/**1014* Determines the integer value of the system property with the1015* specified name.1016*1017* <p>The first argument is treated as the name of a system1018* property. System properties are accessible through the {@link1019* java.lang.System#getProperty(java.lang.String)} method. The1020* string value of this property is then interpreted as an integer1021* value using the grammar supported by {@link Integer#decode decode} and1022* an {@code Integer} object representing this value is returned.1023*1024* <p>The second argument is the default value. An {@code Integer} object1025* that represents the value of the second argument is returned if there1026* is no property of the specified name, if the property does not have1027* the correct numeric format, or if the specified name is empty or1028* {@code null}.1029*1030* <p>In other words, this method returns an {@code Integer} object1031* equal to the value of:1032*1033* <blockquote>1034* {@code getInteger(nm, new Integer(val))}1035* </blockquote>1036*1037* but in practice it may be implemented in a manner such as:1038*1039* <blockquote><pre>1040* Integer result = getInteger(nm, null);1041* return (result == null) ? new Integer(val) : result;1042* </pre></blockquote>1043*1044* to avoid the unnecessary allocation of an {@code Integer}1045* object when the default value is not needed.1046*1047* @param nm property name.1048* @param val default value.1049* @return the {@code Integer} value of the property.1050* @throws SecurityException for the same reasons as1051* {@link System#getProperty(String) System.getProperty}1052* @see java.lang.System#getProperty(java.lang.String)1053* @see java.lang.System#getProperty(java.lang.String, java.lang.String)1054*/1055public static Integer getInteger(String nm, int val) {1056Integer result = getInteger(nm, null);1057return (result == null) ? Integer.valueOf(val) : result;1058}10591060/**1061* Returns the integer value of the system property with the1062* specified name. The first argument is treated as the name of a1063* system property. System properties are accessible through the1064* {@link java.lang.System#getProperty(java.lang.String)} method.1065* The string value of this property is then interpreted as an1066* integer value, as per the {@link Integer#decode decode} method,1067* and an {@code Integer} object representing this value is1068* returned; in summary:1069*1070* <ul><li>If the property value begins with the two ASCII characters1071* {@code 0x} or the ASCII character {@code #}, not1072* followed by a minus sign, then the rest of it is parsed as a1073* hexadecimal integer exactly as by the method1074* {@link #valueOf(java.lang.String, int)} with radix 16.1075* <li>If the property value begins with the ASCII character1076* {@code 0} followed by another character, it is parsed as an1077* octal integer exactly as by the method1078* {@link #valueOf(java.lang.String, int)} with radix 8.1079* <li>Otherwise, the property value is parsed as a decimal integer1080* exactly as by the method {@link #valueOf(java.lang.String, int)}1081* with radix 10.1082* </ul>1083*1084* <p>The second argument is the default value. The default value is1085* returned if there is no property of the specified name, if the1086* property does not have the correct numeric format, or if the1087* specified name is empty or {@code null}.1088*1089* @param nm property name.1090* @param val default value.1091* @return the {@code Integer} value of the property.1092* @throws SecurityException for the same reasons as1093* {@link System#getProperty(String) System.getProperty}1094* @see System#getProperty(java.lang.String)1095* @see System#getProperty(java.lang.String, java.lang.String)1096*/1097public static Integer getInteger(String nm, Integer val) {1098String v = null;1099try {1100v = System.getProperty(nm);1101} catch (IllegalArgumentException | NullPointerException e) {1102}1103if (v != null) {1104try {1105return Integer.decode(v);1106} catch (NumberFormatException e) {1107}1108}1109return val;1110}11111112/**1113* Decodes a {@code String} into an {@code Integer}.1114* Accepts decimal, hexadecimal, and octal numbers given1115* by the following grammar:1116*1117* <blockquote>1118* <dl>1119* <dt><i>DecodableString:</i>1120* <dd><i>Sign<sub>opt</sub> DecimalNumeral</i>1121* <dd><i>Sign<sub>opt</sub></i> {@code 0x} <i>HexDigits</i>1122* <dd><i>Sign<sub>opt</sub></i> {@code 0X} <i>HexDigits</i>1123* <dd><i>Sign<sub>opt</sub></i> {@code #} <i>HexDigits</i>1124* <dd><i>Sign<sub>opt</sub></i> {@code 0} <i>OctalDigits</i>1125*1126* <dt><i>Sign:</i>1127* <dd>{@code -}1128* <dd>{@code +}1129* </dl>1130* </blockquote>1131*1132* <i>DecimalNumeral</i>, <i>HexDigits</i>, and <i>OctalDigits</i>1133* are as defined in section 3.10.1 of1134* <cite>The Java™ Language Specification</cite>,1135* except that underscores are not accepted between digits.1136*1137* <p>The sequence of characters following an optional1138* sign and/or radix specifier ("{@code 0x}", "{@code 0X}",1139* "{@code #}", or leading zero) is parsed as by the {@code1140* Integer.parseInt} method with the indicated radix (10, 16, or1141* 8). This sequence of characters must represent a positive1142* value or a {@link NumberFormatException} will be thrown. The1143* result is negated if first character of the specified {@code1144* String} is the minus sign. No whitespace characters are1145* permitted in the {@code String}.1146*1147* @param nm the {@code String} to decode.1148* @return an {@code Integer} object holding the {@code int}1149* value represented by {@code nm}1150* @exception NumberFormatException if the {@code String} does not1151* contain a parsable integer.1152* @see java.lang.Integer#parseInt(java.lang.String, int)1153*/1154public static Integer decode(String nm) throws NumberFormatException {1155int radix = 10;1156int index = 0;1157boolean negative = false;1158Integer result;11591160if (nm.length() == 0)1161throw new NumberFormatException("Zero length string");1162char firstChar = nm.charAt(0);1163// Handle sign, if present1164if (firstChar == '-') {1165negative = true;1166index++;1167} else if (firstChar == '+')1168index++;11691170// Handle radix specifier, if present1171if (nm.startsWith("0x", index) || nm.startsWith("0X", index)) {1172index += 2;1173radix = 16;1174}1175else if (nm.startsWith("#", index)) {1176index ++;1177radix = 16;1178}1179else if (nm.startsWith("0", index) && nm.length() > 1 + index) {1180index ++;1181radix = 8;1182}11831184if (nm.startsWith("-", index) || nm.startsWith("+", index))1185throw new NumberFormatException("Sign character in wrong position");11861187try {1188result = Integer.valueOf(nm.substring(index), radix);1189result = negative ? Integer.valueOf(-result.intValue()) : result;1190} catch (NumberFormatException e) {1191// If number is Integer.MIN_VALUE, we'll end up here. The next line1192// handles this case, and causes any genuine format error to be1193// rethrown.1194String constant = negative ? ("-" + nm.substring(index))1195: nm.substring(index);1196result = Integer.valueOf(constant, radix);1197}1198return result;1199}12001201/**1202* Compares two {@code Integer} objects numerically.1203*1204* @param anotherInteger the {@code Integer} to be compared.1205* @return the value {@code 0} if this {@code Integer} is1206* equal to the argument {@code Integer}; a value less than1207* {@code 0} if this {@code Integer} is numerically less1208* than the argument {@code Integer}; and a value greater1209* than {@code 0} if this {@code Integer} is numerically1210* greater than the argument {@code Integer} (signed1211* comparison).1212* @since 1.21213*/1214public int compareTo(Integer anotherInteger) {1215return compare(this.value, anotherInteger.value);1216}12171218/**1219* Compares two {@code int} values numerically.1220* The value returned is identical to what would be returned by:1221* <pre>1222* Integer.valueOf(x).compareTo(Integer.valueOf(y))1223* </pre>1224*1225* @param x the first {@code int} to compare1226* @param y the second {@code int} to compare1227* @return the value {@code 0} if {@code x == y};1228* a value less than {@code 0} if {@code x < y}; and1229* a value greater than {@code 0} if {@code x > y}1230* @since 1.71231*/1232public static int compare(int x, int y) {1233return (x < y) ? -1 : ((x == y) ? 0 : 1);1234}12351236/**1237* Compares two {@code int} values numerically treating the values1238* as unsigned.1239*1240* @param x the first {@code int} to compare1241* @param y the second {@code int} to compare1242* @return the value {@code 0} if {@code x == y}; a value less1243* than {@code 0} if {@code x < y} as unsigned values; and1244* a value greater than {@code 0} if {@code x > y} as1245* unsigned values1246* @since 1.81247*/1248public static int compareUnsigned(int x, int y) {1249return compare(x + MIN_VALUE, y + MIN_VALUE);1250}12511252/**1253* Converts the argument to a {@code long} by an unsigned1254* conversion. In an unsigned conversion to a {@code long}, the1255* high-order 32 bits of the {@code long} are zero and the1256* low-order 32 bits are equal to the bits of the integer1257* argument.1258*1259* Consequently, zero and positive {@code int} values are mapped1260* to a numerically equal {@code long} value and negative {@code1261* int} values are mapped to a {@code long} value equal to the1262* input plus 2<sup>32</sup>.1263*1264* @param x the value to convert to an unsigned {@code long}1265* @return the argument converted to {@code long} by an unsigned1266* conversion1267* @since 1.81268*/1269public static long toUnsignedLong(int x) {1270return ((long) x) & 0xffffffffL;1271}12721273/**1274* Returns the unsigned quotient of dividing the first argument by1275* the second where each argument and the result is interpreted as1276* an unsigned value.1277*1278* <p>Note that in two's complement arithmetic, the three other1279* basic arithmetic operations of add, subtract, and multiply are1280* bit-wise identical if the two operands are regarded as both1281* being signed or both being unsigned. Therefore separate {@code1282* addUnsigned}, etc. methods are not provided.1283*1284* @param dividend the value to be divided1285* @param divisor the value doing the dividing1286* @return the unsigned quotient of the first argument divided by1287* the second argument1288* @see #remainderUnsigned1289* @since 1.81290*/1291public static int divideUnsigned(int dividend, int divisor) {1292// In lieu of tricky code, for now just use long arithmetic.1293return (int)(toUnsignedLong(dividend) / toUnsignedLong(divisor));1294}12951296/**1297* Returns the unsigned remainder from dividing the first argument1298* by the second where each argument and the result is interpreted1299* as an unsigned value.1300*1301* @param dividend the value to be divided1302* @param divisor the value doing the dividing1303* @return the unsigned remainder of the first argument divided by1304* the second argument1305* @see #divideUnsigned1306* @since 1.81307*/1308public static int remainderUnsigned(int dividend, int divisor) {1309// In lieu of tricky code, for now just use long arithmetic.1310return (int)(toUnsignedLong(dividend) % toUnsignedLong(divisor));1311}131213131314// Bit twiddling13151316/**1317* The number of bits used to represent an {@code int} value in two's1318* complement binary form.1319*1320* @since 1.51321*/1322@Native public static final int SIZE = 32;13231324/**1325* The number of bytes used to represent a {@code int} value in two's1326* complement binary form.1327*1328* @since 1.81329*/1330public static final int BYTES = SIZE / Byte.SIZE;13311332/**1333* Returns an {@code int} value with at most a single one-bit, in the1334* position of the highest-order ("leftmost") one-bit in the specified1335* {@code int} value. Returns zero if the specified value has no1336* one-bits in its two's complement binary representation, that is, if it1337* is equal to zero.1338*1339* @param i the value whose highest one bit is to be computed1340* @return an {@code int} value with a single one-bit, in the position1341* of the highest-order one-bit in the specified value, or zero if1342* the specified value is itself equal to zero.1343* @since 1.51344*/1345public static int highestOneBit(int i) {1346// HD, Figure 3-11347i |= (i >> 1);1348i |= (i >> 2);1349i |= (i >> 4);1350i |= (i >> 8);1351i |= (i >> 16);1352return i - (i >>> 1);1353}13541355/**1356* Returns an {@code int} value with at most a single one-bit, in the1357* position of the lowest-order ("rightmost") one-bit in the specified1358* {@code int} value. Returns zero if the specified value has no1359* one-bits in its two's complement binary representation, that is, if it1360* is equal to zero.1361*1362* @param i the value whose lowest one bit is to be computed1363* @return an {@code int} value with a single one-bit, in the position1364* of the lowest-order one-bit in the specified value, or zero if1365* the specified value is itself equal to zero.1366* @since 1.51367*/1368public static int lowestOneBit(int i) {1369// HD, Section 2-11370return i & -i;1371}13721373/**1374* Returns the number of zero bits preceding the highest-order1375* ("leftmost") one-bit in the two's complement binary representation1376* of the specified {@code int} value. Returns 32 if the1377* specified value has no one-bits in its two's complement representation,1378* in other words if it is equal to zero.1379*1380* <p>Note that this method is closely related to the logarithm base 2.1381* For all positive {@code int} values x:1382* <ul>1383* <li>floor(log<sub>2</sub>(x)) = {@code 31 - numberOfLeadingZeros(x)}1384* <li>ceil(log<sub>2</sub>(x)) = {@code 32 - numberOfLeadingZeros(x - 1)}1385* </ul>1386*1387* @param i the value whose number of leading zeros is to be computed1388* @return the number of zero bits preceding the highest-order1389* ("leftmost") one-bit in the two's complement binary representation1390* of the specified {@code int} value, or 32 if the value1391* is equal to zero.1392* @since 1.51393*/1394public static int numberOfLeadingZeros(int i) {1395// HD, Figure 5-61396if (i == 0)1397return 32;1398int n = 1;1399if (i >>> 16 == 0) { n += 16; i <<= 16; }1400if (i >>> 24 == 0) { n += 8; i <<= 8; }1401if (i >>> 28 == 0) { n += 4; i <<= 4; }1402if (i >>> 30 == 0) { n += 2; i <<= 2; }1403n -= i >>> 31;1404return n;1405}14061407/**1408* Returns the number of zero bits following the lowest-order ("rightmost")1409* one-bit in the two's complement binary representation of the specified1410* {@code int} value. Returns 32 if the specified value has no1411* one-bits in its two's complement representation, in other words if it is1412* equal to zero.1413*1414* @param i the value whose number of trailing zeros is to be computed1415* @return the number of zero bits following the lowest-order ("rightmost")1416* one-bit in the two's complement binary representation of the1417* specified {@code int} value, or 32 if the value is equal1418* to zero.1419* @since 1.51420*/1421public static int numberOfTrailingZeros(int i) {1422// HD, Figure 5-141423int y;1424if (i == 0) return 32;1425int n = 31;1426y = i <<16; if (y != 0) { n = n -16; i = y; }1427y = i << 8; if (y != 0) { n = n - 8; i = y; }1428y = i << 4; if (y != 0) { n = n - 4; i = y; }1429y = i << 2; if (y != 0) { n = n - 2; i = y; }1430return n - ((i << 1) >>> 31);1431}14321433/**1434* Returns the number of one-bits in the two's complement binary1435* representation of the specified {@code int} value. This function is1436* sometimes referred to as the <i>population count</i>.1437*1438* @param i the value whose bits are to be counted1439* @return the number of one-bits in the two's complement binary1440* representation of the specified {@code int} value.1441* @since 1.51442*/1443public static int bitCount(int i) {1444// HD, Figure 5-21445i = i - ((i >>> 1) & 0x55555555);1446i = (i & 0x33333333) + ((i >>> 2) & 0x33333333);1447i = (i + (i >>> 4)) & 0x0f0f0f0f;1448i = i + (i >>> 8);1449i = i + (i >>> 16);1450return i & 0x3f;1451}14521453/**1454* Returns the value obtained by rotating the two's complement binary1455* representation of the specified {@code int} value left by the1456* specified number of bits. (Bits shifted out of the left hand, or1457* high-order, side reenter on the right, or low-order.)1458*1459* <p>Note that left rotation with a negative distance is equivalent to1460* right rotation: {@code rotateLeft(val, -distance) == rotateRight(val,1461* distance)}. Note also that rotation by any multiple of 32 is a1462* no-op, so all but the last five bits of the rotation distance can be1463* ignored, even if the distance is negative: {@code rotateLeft(val,1464* distance) == rotateLeft(val, distance & 0x1F)}.1465*1466* @param i the value whose bits are to be rotated left1467* @param distance the number of bit positions to rotate left1468* @return the value obtained by rotating the two's complement binary1469* representation of the specified {@code int} value left by the1470* specified number of bits.1471* @since 1.51472*/1473public static int rotateLeft(int i, int distance) {1474return (i << distance) | (i >>> -distance);1475}14761477/**1478* Returns the value obtained by rotating the two's complement binary1479* representation of the specified {@code int} value right by the1480* specified number of bits. (Bits shifted out of the right hand, or1481* low-order, side reenter on the left, or high-order.)1482*1483* <p>Note that right rotation with a negative distance is equivalent to1484* left rotation: {@code rotateRight(val, -distance) == rotateLeft(val,1485* distance)}. Note also that rotation by any multiple of 32 is a1486* no-op, so all but the last five bits of the rotation distance can be1487* ignored, even if the distance is negative: {@code rotateRight(val,1488* distance) == rotateRight(val, distance & 0x1F)}.1489*1490* @param i the value whose bits are to be rotated right1491* @param distance the number of bit positions to rotate right1492* @return the value obtained by rotating the two's complement binary1493* representation of the specified {@code int} value right by the1494* specified number of bits.1495* @since 1.51496*/1497public static int rotateRight(int i, int distance) {1498return (i >>> distance) | (i << -distance);1499}15001501/**1502* Returns the value obtained by reversing the order of the bits in the1503* two's complement binary representation of the specified {@code int}1504* value.1505*1506* @param i the value to be reversed1507* @return the value obtained by reversing order of the bits in the1508* specified {@code int} value.1509* @since 1.51510*/1511public static int reverse(int i) {1512// HD, Figure 7-11513i = (i & 0x55555555) << 1 | (i >>> 1) & 0x55555555;1514i = (i & 0x33333333) << 2 | (i >>> 2) & 0x33333333;1515i = (i & 0x0f0f0f0f) << 4 | (i >>> 4) & 0x0f0f0f0f;1516i = (i << 24) | ((i & 0xff00) << 8) |1517((i >>> 8) & 0xff00) | (i >>> 24);1518return i;1519}15201521/**1522* Returns the signum function of the specified {@code int} value. (The1523* return value is -1 if the specified value is negative; 0 if the1524* specified value is zero; and 1 if the specified value is positive.)1525*1526* @param i the value whose signum is to be computed1527* @return the signum function of the specified {@code int} value.1528* @since 1.51529*/1530public static int signum(int i) {1531// HD, Section 2-71532return (i >> 31) | (-i >>> 31);1533}15341535/**1536* Returns the value obtained by reversing the order of the bytes in the1537* two's complement representation of the specified {@code int} value.1538*1539* @param i the value whose bytes are to be reversed1540* @return the value obtained by reversing the bytes in the specified1541* {@code int} value.1542* @since 1.51543*/1544public static int reverseBytes(int i) {1545return ((i >>> 24) ) |1546((i >> 8) & 0xFF00) |1547((i << 8) & 0xFF0000) |1548((i << 24));1549}15501551/**1552* Adds two integers together as per the + operator.1553*1554* @param a the first operand1555* @param b the second operand1556* @return the sum of {@code a} and {@code b}1557* @see java.util.function.BinaryOperator1558* @since 1.81559*/1560public static int sum(int a, int b) {1561return a + b;1562}15631564/**1565* Returns the greater of two {@code int} values1566* as if by calling {@link Math#max(int, int) Math.max}.1567*1568* @param a the first operand1569* @param b the second operand1570* @return the greater of {@code a} and {@code b}1571* @see java.util.function.BinaryOperator1572* @since 1.81573*/1574public static int max(int a, int b) {1575return Math.max(a, b);1576}15771578/**1579* Returns the smaller of two {@code int} values1580* as if by calling {@link Math#min(int, int) Math.min}.1581*1582* @param a the first operand1583* @param b the second operand1584* @return the smaller of {@code a} and {@code b}1585* @see java.util.function.BinaryOperator1586* @since 1.81587*/1588public static int min(int a, int b) {1589return Math.min(a, b);1590}15911592/** use serialVersionUID from JDK 1.0.2 for interoperability */1593@Native private static final long serialVersionUID = 1360826667806852920L;1594}159515961597