【问题标题】:Understanding Java Integer.parseInt(String s, int radix) source code理解 Java Integer.parseInt(String s, int radix) 源代码
【发布时间】:2018-01-20 11:03:45
【问题描述】:

我正在查看 java.lang.Integer 的 parseInt 方法的源代码。

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("s == 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;
}

我可以看到multmin 以某种方式被用于检测正反两面的整数溢出。但我很难理解如何。

我也不明白为什么我们在计算时将结果保持为负数,如果没有检测到负数,则在最后将其设为正数。

【问题讨论】:

    标签: java integer integer-overflow


    【解决方案1】:

    此方法旨在在s 表示的整数超出[Integer.MIN_VALUE, Integer.MAX_VALUE][-2147483648, 2147483647] 范围时抛出异常。

    算法执行重复的乘法和加法,最终可能导致溢出。该算法通过提前检查操作数来避免溢出。

    检查溢出

    检查result + digit 是否会导致溢出而不实际添加它们的最简单方法是检查:

    if (result > limit - digit) // result, limit and digit are positive
    

    检查result * radix 是否会导致溢出而不实际相乘的最简单方法是检查:

    if (result > limit / radix) // result, limit and radix are positive
    

    这就解释了limit = Integer.MAX...multmin = limit / radix 的作用。

    为什么要“负积累”?

    算法分离出符号并对剩余的数字进行操作(处理一种情况更容易)。它必须处理的一种特殊情况是-2147483648;在这种情况下,限制必须设置为2147483648,这超出了Integer 的范围。

    对于负累积,限制可以设置为-2147483648。请注意,上述“if”条件必须针对负数进行如下调整:

    if (result < limit + digit) // result and limit are negative
    if (result < limit / radix) // result and limit are negative
    

    以下是算法内部每一步发生的粗略概述:

    // parseInt("123", 10)
      limit: -2147483647 (-Integer.MAX_VALUE)
    multmin: -214748364
     result: -1
     result: -12
     result: -123
    
    // parseInt("2147483648", 10)
      limit: -2147483647 (-Integer.MAX_VALUE)
    multmin: -214748364
     result: -2
     result: -21
     result: -214
     result: -2147
     result: -21474
     result: -214748
     result: -2147483
     result: -21474836
     result: -214748364
     result: Overflow (after multiplication, before subtraction)
    

    【讨论】:

      【解决方案2】:

      multmin 是如何工作的?

      multmin 用于以下代码:

      if (result < multmin) {
          throw NumberFormatException.forInputString(s);
      }
      
      • 如果当前结果小于multmin,则下一代结果 必须溢出,所以抛出异常:

        if result < multmin, ------> result < limit / radix (beacause multmin = limit / radix) ------> result * radix < limit ------> result * radix - digit < limit (overflow).

      • 如果当前结果大于等于multmin,我们可以 断言 result * radix &gt;= limit 没有溢出,所以继续检查result * radix - digit 是否溢出:

        if (result < limit + digit) { throw NumberFormatException.forInputString(s); }

      为什么要用负数?

      因为Integer.MIN_VALUE(-2147483648)绝对 值大于Integer.MAX_VALUE (2147483647)

      假设我们有一个POSITIVE版本,当输入数字以'+'开头时,我们可以将limit设置为Integer.MAX_VALUE。 但是,当输入数字以'-'开头时,我们不能将limit设置为2147483648,这是一个溢出值。

      【讨论】:

        猜你喜欢
        • 2014-05-26
        • 2013-02-19
        • 1970-01-01
        • 1970-01-01
        • 2011-12-05
        • 1970-01-01
        • 2020-02-18
        • 2011-07-26
        • 1970-01-01
        相关资源
        最近更新 更多