Mike Vella
Mike Vella

Reputation: 10575

Binary as list of 1s and 0s to int

I would like to convert a list of integer 1s and 0s which represent a binary number to an int.

something along the lines of:

>>> [1,1,0,1].toint()

would give an output of 13

Upvotes: 4

Views: 830

Answers (3)

user2555451
user2555451

Reputation:

Look at this:

>>> x = [1,1,0,1]
>>> int("".join(map(str, x)), 2)
13
>>>

Upvotes: 3

arshajii
arshajii

Reputation: 129507

Strings are unnecessary here:

>>> l = [1,1,0,1]
>>> 
>>> sum(j<<i for i,j in enumerate(reversed(l)))
13

Relevant documentation:

Upvotes: 16

Simeon Visser
Simeon Visser

Reputation: 122376

You can do:

>>> int(''.join(map(str, my_list)), 2)
5

Upvotes: 4

Related Questions