整数是如何转换为字符串的? [英] How are integers converted to strings under the hood?

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

问题描述

我想真正的问题是如何将 base2/binary 转换为 base10.最常见的应用可能是为输出创建字符串:将一组二进制数字数据转换为字符数组.这是如何做到的?

I suppose the real question is how to convert base2/binary to base10. The most common application of this would probably be in creating strings for output: turning a chunk of binary numerical data into an array of characters. How exactly is this done?

我的猜测:看到可能没有为每个数值预定义的字符串,我猜测计算机从右到左遍历整数的每一位,每次增加 char 数组/base10 符号位置中的适当值.如果我们取二进制数 160(10100000),它会知道第 8 位的 1 表示 128,因此它将 1 放入第三列,将 2 放入第二列,将 8 放入第三列.第 6 列中的 1 表示 32,它会将这些值添加到第二位和第一位,并在需要时进行结转.在此之后,它很容易转换为实际的字符代码.

my guess: Seeing as there probably isn't a string predefined for each numerical value, I'm guessing that the computer goes through each bit of the integer from right to left, each time incrementing the appropriate values in the char array/base10 notation places. If we take the number 160 in binary (10100000), it would know that a 1 in the 8th place means 128, so it places 1 into the third column, 2 in the second, and 8 in the third. The 1 in the 6th column means 32, and it would add those values to the second and first place, carrying over if needed. After this it's an easy conversion to actual char codes.

推荐答案

while number != 0:
    nextdigit = number % 10
    AddToLeft(result, convert nextdigit to char)
    number = number / 10

留给读者练习处理零和负数.

It's left as an exercise for the reader to handle zero and negative numbers.

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

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