简体   繁体   中英

How to convert strings representation of binary into binary?

I'm trying to convert strings representing binaries such as '000', '00', '010' or '00001' into binaries (000, 00, 010 and 00001) I've tried the following code but it deletes the zeros on the left.

binaries=['000','00','010,'00000']
resultArray = []
    for binary in binaries:
        resultArray.append(int(binary))
print resultArray

The results is

[0, 0, 10, 0]

instead of the desired

[000, 00, 010, 00000]

I also tried:

binaries=['000','00','010,'00000']
resultArray = []
    for binary in binaries:
        resultArray.append(format(int(binary), '02x'))
print resultArray

but then I get the following results

['00', '00', '1010', '00']

It happens because int() has a (optional) second argument for specifying the base, which is by default 10. So basically, you convert 0100 (hundred) to 100 (again, hundred).

Try:

int(binary_string, 2)

and:

bin(number)

And what the leading zeros goes, it's a bit difficult to do it in general, as there is no difference between 000 and 0 . To put it differently, there is no such thing as:

[000, 00, 010, 00000]

only:

[0, 0, 2, 0] (list of numbers, read by humans in base 10)

What you can try to do is:

bin(number)[2:].zfill(known_width)

Your desired list is impossible to create. Integers do not have zeros in front however hard you try. The only way to have zeros at the beginning of your number is to make it a string, but that is what you already have, so I don't think it is necessary for me to show you how to convert strings to strings. If the zeroes aren't important, than what you have for conversion does the job. You could make it simpler with resultArray = list(map(int, binaries)) , but you just can't have an integer with a zero at the beginning.

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