最近被问到这个问题,不知道答案。有人可以从高层次解释 Java 如何获取字符/字符串并将其转换为 int。
原文由 Karl 发布,翻译遵循 CC BY-SA 4.0 许可协议
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 许可协议
4 回答1.2k 阅读✓ 已解决
4 回答1.2k 阅读✓ 已解决
1 回答2.5k 阅读✓ 已解决
2 回答705 阅读✓ 已解决
2 回答1.7k 阅读
2 回答1.6k 阅读
2 回答1.3k 阅读
通常这样做是这样的:
编辑:如果您将 10 替换为正确的基数并调整从相应字符中获取数字,则这适用于任何基数(对于小于 10 的基数应该按原样工作,但需要对更高的基数进行一些调整 - 如十六进制 -因为字母与数字相隔 7 个字符)。
编辑 2 :字符到数字值的转换:字符“0”到“9”的 ASCII 值是 48 到 57(六进制的 0x30 到 0x39),因此为了将字符转换为其数字值,需要一个简单的减法。通常它是这样完成的(其中 ord 是给出字符 ASCII 码的函数):
对于更高的数字基数,字母被用作“数字”(十六进制的 AF),但字母从 65(六进制 0x41)开始,这意味着我们必须考虑到一个间隙:
示例:’B’ 是 66,所以 ord(‘B’) - ord(‘0’) = 18。由于 18 大于 9,我们减去 7,最终结果将是 11 - ‘digit’ B 的值.
这里还有一点要注意——这只适用于大写字母,所以数字必须先转换为大写。