Integer.parseInt()源碼

character.digit(char ch, int radix)  將radix進制的ch轉化成十進制數;java

character.digit(int codePoint, int radix)     將radix進制的askll碼對應的char轉化成十進制數。git

例:String s=2147483648less

result初始值爲0,code

limit= -Integer.MAX_VALUE,即 -2147483647,orm

上一個result和limit比較,排除21474836471這種越界的狀況it

result*10和limit+當前位比較,排除2147483648這種越界的狀況(-2147483640<-2147483647+8)io

result-=當前位class

public static int parseInt(String s) throws NumberFormatException {
        return parseInt(s,10);
    }

    public static int parseInt(String s, int radix)
                throws NumberFormatException
    {

        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;
    }
相關文章
相關標籤/搜索