user3051330
user3051330

Reputation: 11

Converting a list of numbers into a binary number base 10

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

Answers (3)

Aswin Murugesh
Aswin Murugesh

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

Nafiul Islam
Nafiul Islam

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

thefourtheye
thefourtheye

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

Related Questions