public static int parseInt(String s, int radix)
throws NumberFormatException
{
/*
* WARNING: This method may be invoked early during VM initialization
* before IntegerCache is initialized. Care must be taken to not use
* the valueOf method.
*/

if (s == null) { // 如果接受的字符串为空, 就报空字符串的异常
throw new NumberFormatException("null");
}

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;
boolean negative = false; // 判断符号
int i = 0, len = s.length(); // 设置初始位置和字符串的长度
int limit = -Integer.MAX_VALUE;
int multmin;
int digit;

if (len > 0) { // 字符串的长度必须大于零
char firstChar = s.charAt(0); // 获得字符串的第一个字符
if (firstChar < '0') { // Possible leading "+" or "-"  //判断是符号而非数字
if (firstChar == '-') {
negative = true;
limit = Integer.MIN_VALUE;
} else if (firstChar != '+') // 如果不为++的话就报错
throw NumberFormatException.forInputString(s);
// 字符串的长度为1但是又不是数字, 那肯定就出错了
if (len == 1) // Cannot have lone "+" or "-"
throw NumberFormatException.forInputString(s);
i++;
}
multmin = limit / radix;

/*
* 下面的过程其实很好理解, 以8进制的"534"为例
* (-5*8-3)*8-4 = -348, 根据符号位判断返回的是348
*/

while (i < len) {
// Accumulating negatively avoids surprises near MAX_VALUE

// 除了前面的判断这里的也有点复杂, 因为要考虑到各种进位
// 这个将i位置上的字符根据基数转为实际的值, A->11
digit = Character.digit(s.charAt(i++),radix);
if (digit < 0) {
throw NumberFormatException.forInputString(s);
}
if (result < multmin) {
throw NumberFormatException.forInputString(s);
}
result *= radix;
if (result < limit + digit) {
throw NumberFormatException.forInputString(s);
}
result -= digit;
}
} else {
throw NumberFormatException.forInputString(s);
}
return negative ? result : -result; // 根据符号位来判断返回哪一个
}

 

也就是说大致上的思路是:传入字符串与基数,一般基数默认为10进制,然后对字符串进行条件判断,不能为空,基数的范围在2进制到36进制之间;再将字符串一个一个从前往后读进去,第一位判读尤其重要根据firstChar < '0'判断是数字还是正负号,如果是符号,最后结果要取反;然后将接下来的字符一个一个根据所在的位与基数进行相乘,这里可以用最简单的数字乘以幂,或者使用这种代码中的方法进行计算,最后根据符号位返回结果。