简体   繁体   English

为什么二进制数的str(num)只返回特定的数字作为字符串?

[英]Why does str(num) for binary number return only specific digits as string?

I have a number 000000000000001011 and I want to iterate over this. 我有一个数字000000000000001011,我想迭代这个。 I used str(num) to iterate over it but it returns '11' as output string. 我使用str(num)迭代它,但它返回'11'作为输出字符串。 Why does this happen? 为什么会这样?

There's a couple of things at play here. 这里有几件事情在起作用。

First, when the number is input, it is converted from string to integer format with the number-system specified (or that's my understanding from the question anyway): 首先,当输入数字时,它会从字符串转换为整数格式,并指定数字系统(或者我对问题的理解):

number = int( user_input_str, 2 )  # user_input_str given in binary

But once it's stored internally, extraneous digits (for all intents and purposes) are now gone. 但是一旦它被存储在内部,无关数字(用于所有意图和目的)现在都消失了。

To iterate over the digits, you'd need to convert it back to a binary string: 要遍历数字,您需要将其转换回二进制字符串:

number_str = '{0:b}'.format( number ).zfill( 18 )

or without leading zeros: 或者没有前导零:

number_str = '{0:b}'.format( number )

This can then be iterated over easily: 然后可以轻松地迭代:

for digit in number_str:
    # do whatever with each digit

Failing all that, just iterate over the user's input without the in-between conversion steps. 如果做不到这一点,只需迭代用户的输入而不进行中间转换步骤。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM