Java中Integer.parse()的學(xué)習(xí)總結(jié)

字號:


    內(nèi)部使用負(fù)數(shù)表示
    當(dāng)函數(shù)還未考慮到符號影響時候,內(nèi)部是用負(fù)數(shù)來表示逐步轉(zhuǎn)換的結(jié)果。
    初看到下面兩句,很是疑惑。
    int max = Integer.MIN_VALUE / radix;
    int next = result * radix - digit;
    為什么要用負(fù)數(shù)來表示呢?正數(shù)才比較符號平常頭腦的思路。
    我的想法是,負(fù)數(shù)部分是0~-2147483648,而正數(shù)部分是0~2147483647,負(fù)數(shù)范圍比正數(shù)范圍廣。如果內(nèi)部是用正數(shù)的話,"-2147483648"這個字符串處理就更復(fù)雜點,因為正數(shù)沒法表示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的絕對值已經(jīng)大于max的絕對值,那么result再增加一位必超出范圍。
    //int max = Integer.MIN_VALUE / radix; 這是max定義。
    if (max > result) {
    throw invalidInt(string);
    }
    int next = result * radix - digit;
    //可能出現(xiàn)overflow的現(xiàn)象。
    //如:如果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;
    }