How compiler is converting integer to string and vice versa

后端 未结 3 1926
时光说笑
时光说笑 2021-01-05 05:24

Many languages have functions for converting string to integer and vice versa. So what happens there? What algorithm is being executed during conversion?

I don\'t as

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-05 05:53

    String to integer:

    Many (most) languages represent strings, on some level or another, as an array (or list) of characters, which are also short integers. Map the ones corresponding to number characters to their number value. For example, '0' in ascii is represented by 48. So you map 48 to 0, 49 to 1, and so on to 9.

    Starting from the left, you multiply your current total by 10, add the next character's value, and move on. (You can make a larger or smaller map, change the number you multiply by at each step, and convert strings of any base you like.)

    Integer to string is a longer process involving base conversion to 10. I suppose that since most integers have limited bits (32 or 64, usually), you know that it will come to a certain number of characters at most in a string (20?). So you can set up your own adder and iterate through each place for each bit after calculating its value (2^place).

提交回复
热议问题