简体   繁体   中英

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. I used str(num) to iterate over it but it returns '11' as output string. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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