Reputation: 11
How do you convert a list of 0 and 1's into a binary number with base 10?
For example: ([0,0,1,0,0,1])
will give me 9
Upvotes: 1
Views: 5551
Reputation: 11070
try this:
int("".join(str(x) for x in a),2)
Convert the list into a string. And then make the binary to decimal conversion
Upvotes: 8
Reputation: 82470
Well this is quite simple:
>>> a = [0,0,1,0,0,1]
>>> s = "".join(map(str, a))
>>> s
'001001'
>>> int(s, base=2)
9
Upvotes: 4
Reputation: 239473
You can use int
function with the second parameter which indicates the base. As, the list is full of numbers, that has to be converted to a string (int
accepts only string), so we do map(str, data)
print "".join(map(str, data))
Output
001001
So, it boils down to this
data = [0,0,1,0,0,1]
print int("".join(map(str, data)), 2)
Output
9
Upvotes: 0