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

查看:90
本文介绍了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.

非常感谢

Karl

编辑:如果其他语言也做类似的事情也会很好。

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

推荐答案

通常这样做:


  • 初始结果为0

  • 为字符串中的每个字符执行此操作


    • 结果=结果* 10

    • get字符中的数字('0'是48 ASCII(或0x30),所以只需从字符ASCII码中减去该数字即可获得数字)

    • 将数字添加到结果中

    • init result with 0
    • for each character in string do this
      • result = result * 10
      • get the digit from the character ('0' is 48 ASCII (or 0x30), so just subtract that from the character ASCII code to get the digit)
      • add the digit to the result

      编辑:如果你用正确的基数替换10并且从相应的字符中调整数字的获取(这应该适用于低于10的基数,但是需要稍微调整一下),这适用于任何基数r个基数 - 比如十六进制 - 因为字母与数字分开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')
      

      对于更高的数字基数,这些字母用作'数字'(六进制中的AF),但字母从65开始(0x41 hexa),这意味着我们必须考虑到的差距:

      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天全站免登陆