Integer.parseInt(string) 实际上是如何工作的? [英] How does Integer.parseInt(string) actually work?

查看:25
本文介绍了Integer.parseInt(string) 实际上是如何工作的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Was asked this question recently and did not know the answer. From a high level can someone explain how Java takes a character / String and convert it into an int.

非常感谢

卡尔

如果其他语言也做类似的事情,也很高兴知道.

Would also be good to know if other languages do a similar sort of thing as well.

推荐答案

通常这样做:

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

    编辑:这适用于任何基数,如果你用正确的基数替换 10 并调整从相应字符中获取数字(应该对低于 10 的基数起作用,但需要对更高的基数稍作调整 - 如十六进制 - 因为字母与数字被 7 个字符分隔).

    Edit: This works for any base if you replace 10 with the correct base and adjust the obtaining of the digit from the corresponding character (should work as is for bases lower than 10, but would need a little adjusting for higher bases - like hexadecimal - since letters are separated from numbers by 7 characters).

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

    Edit 2: Char to digit value conversion: characters '0' to '9' have ASCII values 48 to 57 (0x30 to 0x39 in hexa), so in order to convert a character to its digit value a simple subtraction is needed. Usually it's done like this (where ord is the function that gives the ASCII code of the character):

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

    对于更高的数字基数,字母用作数字"(六进制中的 A-F),但字母从 65(0x41 六进制)开始,这意味着我们必须考虑到一个差距:

    For higher number bases the letters are used as 'digits' (A-F in hexa), but letters start from 65 (0x41 hexa) which means there's a gap that we have to account for:

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

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

    Example: 'B' is 66, so ord('B') - ord('0') = 18. Since 18 is larger than 9 we subtract 7 and the end result will be 11 - the value of the 'digit' B.

    这里还有一点需要注意 - 这仅适用于大写字母,因此必须先将数字转换为大写.

    One more thing to note here - this works only for uppercase letters, so the number must be first converted to uppercase.

    这篇关于Integer.parseInt(string) 实际上是如何工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆