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

本文探讨了在Android源代码及JDK中如何使用负数进行字符串到整数的转换,解释了为何选择负数表示法,并通过代码详细展示了这一过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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


转载于:https://my.oschina.net/u/582355/blog/361529

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值