首页 > 代码库 > Java中Integer.parse()的学习总结

Java中Integer.parse()的学习总结

内部使用负数表示

当函数还未考虑到符号影响时候,内部是用负数来表示逐步转换的结果。

初看到下面两句,很是疑惑。

int max = Integer.MIN_VALUE / radix;

int next = result * radix - digit;

为什么要用负数来表示呢?正数才比较符号平常头脑的思路。

我的想法是,负数部分是0~-2147483648,而正数部分是0~2147483647,负数范围比正数范围广。如果内部是用正数的话,"-2147483648"这个字符串处理就更复杂点,因为正数没法表示2147483648。

其他的理解放在下面代码注释中:

    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;
    }


Java中Integer.parse()的学习总结