public static int parseInt(String s, int radix)
throws NumberFormatException
{
if (s == null) {
throw new NumberFormatException("null");
}
//Determine the range of the decimal parsing, only support 2-36 decimal, the default is decimal, redix = 10
if (radix < Character.MIN_RADIX) {
throw new NumberFormatException("radix " + radix +
" less than Character.MIN_RADIX");
}
if (radix > Character.MAX_RADIX) {
throw new NumberFormatException("radix " + radix +
" greater than Character.MAX_RADIX");
}
int result = 0;//Parsing results
boolean negative = false;// Negative marking
int i = 0, len = s.length();
int limit = -Integer.MAX_VALUE;// Threshold for parsing results, i.e., not parsing the maximum number that can be represented by an integer.
int multmin;
int digit;
if (len > 0) {
// The following is the symbol detection, detect whether the first character is a negative sign, and update the parsing limit according to the negative sign, i.e., the parsing result can not exceed the maximum value of int type.
char firstChar = s.charAt(0);
if (firstChar < '0') { // Possible leading "+" or "-"
if (firstChar == '-') {
negative = true;
limit = Integer.MIN_VALUE;// If negative, limit the value to the smallest integer.
} else if (firstChar != '+')
throw NumberFormatException.forInputString(s);
if (len == 1) // Cannot have lone "+" or "-"
throw NumberFormatException.forInputString(s);
i++;
}
multmin = limit / radix;
while (i < len) {// Loop through each character
// Accumulating negatively avoids surprises near MAX_VALUE
digit = Character.digit(s.charAt(i++),radix);//Conversion of characters to numbers
if (digit < 0) {// Parsed a single negative number, threw an exception.
throw NumberFormatException.forInputString(s);
}
if (result < multmin) {//Results parsing has exceeded the limit, because the back to continue * 10, here the result if it has been larger than Integer.MAX_VALUE/10, then the number is over, throw an exception
throw NumberFormatException.forInputString(s);
}
result *= radix;//Multiply by 10
if (result < limit + digit) {// As in the previous step, to prevent exceeding the Integer expression range
throw NumberFormatException.forInputString(s);
}
result -= digit;
}
} else {
throw NumberFormatException.forInputString(s);
}
return negative ? result : -result;//Take the opposite number and return
}