Reputation: 115
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']
Upvotes: 0
Views: 189
Reputation: 11468
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)
Upvotes: 2
Reputation: 20336
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.
Upvotes: 1