Integer.parseInt(string) 是如何工作的?

新手上路,请多包涵

最近被问到这个问题,不知道答案。有人可以从高层次解释 Java 如何获取字符/字符串并将其转换为 int。

原文由 Karl 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 516
2 个回答

通常这样做是这样的:

  • 初始结果为 0
  • 对字符串中的每个字符执行此操作
    • 结果 = 结果 \* 10
    • 从字符中获取数字(’0’ 是 48 ASCII(或 0x30),因此只需从字符 ASCII 码中减去它即可获取数字)
    • 将数字添加到结果
  • 返回结果

编辑:如果您将 10 替换为正确的基数并调整从相应字符中获取数字,则这适用于任何基数(对于小于 10 的基数应该按原样工作,但需要对更高的基数进行一些调整 - 如十六进制 -因为字母与数字相隔 7 个字符)。

编辑 2 :字符到数字值的转换:字符“0”到“9”的 ASCII 值是 48 到 57(六进制的 0x30 到 0x39),因此为了将字符转换为其数字值,需要一个简单的减法。通常它是这样完成的(其中 ord 是给出字符 ASCII 码的函数):

 digit = ord(char) - ord('0')

对于更高的数字基数,字母被用作“数字”(十六进制的 AF),但字母从 65(六进制 0x41)开始,这意味着我们必须考虑到一个间隙:

 digit = ord(char) - ord('0')
if digit > 9 then digit -= 7

示例:’B’ 是 66,所以 ord(‘B’) - ord(‘0’) = 18。由于 18 大于 9,我们减去 7,最终结果将是 11 - ‘digit’ B 的值.

这里还有一点要注意——这只适用于大写字母,所以数字必须先转换为大写。

原文由 rslite 发布,翻译遵循 CC BY-SA 2.5 许可协议

Java API 的源代码是免费提供的。这是 parseInt() 方法。它相当长,因为它必须处理很多特殊情况和极端情况。

 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, max = s.length();
    int limit;
    int multmin;
    int digit;

    if (max > 0) {
        if (s.charAt(0) == '-') {
            negative = true;
            limit = Integer.MIN_VALUE;
            i++;
        } else {
            limit = -Integer.MAX_VALUE;
        }
        multmin = limit / radix;
        if (i < max) {
            digit = Character.digit(s.charAt(i++), radix);
            if (digit < 0) {
                throw NumberFormatException.forInputString(s);
            } else {
                result = -digit;
            }
        }
        while (i < max) {
            // 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);
    }
    if (negative) {
        if (i > 1) {
            return result;
        } else { /* Only got "-" */
            throw NumberFormatException.forInputString(s);
        }
    } else {
        return -result;
    }
}

原文由 Michael Borgwardt 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题