2014.12.29
下面的写的总结是关于android源代码中的实现。jdk1.8.0_25源代码中的实现不同,但是思想类似,都是使用负数表示。我更喜欢android中的实现。
内部使用负数表示
当函数还未考虑到符号影响时候,内部是用负数来表示逐步转换的结果。
初看到下面两句,很是疑惑。
int max = Integer.MIN_VALUE / radix;
int next = result * radix - digit;
为什么要用负数来表示呢?正数才比较符号平常头脑的思路。
我的想法是,负数部分是0~-2147483648,而正数部分是0~2147483647,负数范围比正数范围广。如果内部是用正数的话,"-2147483648"这个字符串处理就更复杂点,因为正数没法表示2147483648。
其他的理解放在下面代码注释中(Android):
private static int parse(String string, int offset, int radix, boolean negative) throws NumberFormatException {
// Why is Integer.MIN_VALUE is choosed? Not Integer.MAX_VALUE ?
// Maybe because the range in the minus side is greater than that in the plus side
int max = Integer.MIN_VALUE / radix;
int result = 0;
int length = string.length();
while (offset < length) {
int digit = Character.digit(string.charAt(offset++), radix);
if (digit == -1) {
throw invalidInt(string);
}
//如果此时的result的绝对值已经大于max的绝对值,那么result再增加一位必超出范围。
//int max = Integer.MIN_VALUE / radix; 这是max定义。
if (max > result) {
throw invalidInt(string);
}
int next = result * radix - digit;
//可能出现overflow的现象。
//如:如果radix为10,上面result等于-214748364,又digit大于8,则next会超出范围。
if (next > result) {
throw invalidInt(string);
}
result = next;
}
if (!negative) {
result = -result;
// when result equals to 80000000H, -result equals to result.
if (result < 0) {
throw invalidInt(string);
}
}
return result;
}
以下是jdk1.8.0_25中的源代码
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);
if (len == 1) // Cannot have lone "+" or "-"
throw NumberFormatException.forInputString(s);
i++;
}
multmin = limit / radix;
while (i < len) {
// Accumulating negatively avoids surprises near MAX_VALUE
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;
}