Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binary as list of 1s and 0s to int

Tags:

python

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

like image 306
Mike Vella Avatar asked Nov 29 '22 15:11

Mike Vella


2 Answers

Strings are unnecessary here:

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

Relevant documentation:

  • sum()
  • enumerate()
  • reversed()
like image 90
arshajii Avatar answered Dec 11 '22 06:12

arshajii


You can do:

>>> int(''.join(map(str, my_list)), 2)
5
like image 43
Simeon Visser Avatar answered Dec 11 '22 07:12

Simeon Visser