如何编译器转换成整数,字符串,反之亦然 [英] How compiler is converting integer to string and vice versa

查看:147
本文介绍了如何编译器转换成整数,字符串,反之亦然的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

许多语言有功能将字符串转换为整数,反之亦然。所以会发生什么呢?转换过程中所执行的是什么算法?

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 ask in specific language because I think it should be similar in all of them.

推荐答案

要字符串转换为整数,取每个字符反过来,如果它在'0'到'9',其转换为十进制数。通常这简直是减去'0'的字符值。现在乘以10的任何previous结果,并添加新的价值。重复,直到没有离开数字。如果有一个领先的' - '减号,颠倒结果

To convert a string to an integer, take each character in turn and if it's in the range '0' through '9', convert it to its decimal equivalent. Usually that's simply subtracting the character value of '0'. Now multiply any previous results by 10 and add the new value. Repeat until there are no digits left. If there was a leading '-' minus sign, invert the result.

要一个整数转换为字符串,通过转换号码,如果是负数开始。除以10的整数,并保存余数。通过添加0的字符值转换到其余的字符。按下该字符串的开头;现在重复使用从分割而得到的值。重复,直到分割值为零。摆了个领先 - 。减号如果数字开始了负

To convert an integer to a string, start by inverting the number if it is negative. Divide the integer by 10 and save the remainder. Convert the remainder to a character by adding the character value of '0'. Push this to the beginning of the string; now repeat with the value that you obtained from the division. Repeat until the divided value is zero. Put out a leading '-' minus sign if the number started out negative.

下面是用Python,这在我看来是最接近伪code语言的具体实现。

Here are concrete implementations in Python, which in my opinion is the language closest to pseudo-code.

def string_to_int(s):
    i = 0
    sign = 1
    if s[0] == '-':
        sign = -1
        s = s[1:]
    for c in s:
        if not ('0' <= c <= '9'):
            raise ValueError
        i *= 10
        i += ord(c) - ord('0')
    i *= sign
    return i

def int_to_string(i):
    s = ''
    sign = ''
    if i < 0:
        sign = '-'
        i = -i
    while True:
        remainder = i % 10
        i = i / 10
        s = chr(ord('0') + remainder) + s
        if i == 0:
            break
    s = sign + s
    return s

这篇关于如何编译器转换成整数,字符串,反之亦然的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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