Bits list to integer in Python

28,911

Solution 1

You can use bitshifting:

out = 0
for bit in bitlist:
    out = (out << 1) | bit

This easily beats the "int cast" method proposed by A. R. S., or the modified cast with lookup proposed by Steven Rumbalski:

>>> def intcaststr(bitlist):
...     return int("".join(str(i) for i in bitlist), 2)
... 
>>> def intcastlookup(bitlist):
...     return int(''.join('01'[i] for i in bitlist), 2)
... 
>>> def shifting(bitlist):
...     out = 0
...     for bit in bitlist:
...         out = (out << 1) | bit
...     return out
... 
>>> timeit.timeit('convert([1,0,0,0,0,0,0,0])', 'from __main__ import intcaststr as convert', number=100000)
0.5659139156341553
>>> timeit.timeit('convert([1,0,0,0,0,0,0,0])', 'from __main__ import intcastlookup as convert', number=100000)
0.4642159938812256
>>> timeit.timeit('convert([1,0,0,0,0,0,0,0])', 'from __main__ import shifting as convert', number=100000)
0.1406559944152832

Solution 2

...or using the bitstring module

>>> from bitstring import BitArray
>>> bitlist=[1,0,0,0,0,0,0,0]
>>> b = BitArray(bitlist)
>>> b.uint
128

Solution 3

Try this one-liner:

int("".join(str(i) for i in my_list), 2)

If you're concerned with speed/efficiency, take a look at Martijn Pieters' solution.

Solution 4

I came across a method that slightly outperforms Martijn Pieters solution, though his solution is prettier of course. I am actually a bit surprised by the results, but anyway...

import timeit

bit_list = [1,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0]

def mult_and_add(bit_list):
    output = 0
    for bit in bit_list:
        output = output * 2 + bit
    return output

def shifting(bitlist):
     out = 0
     for bit in bitlist:
         out = (out << 1) | bit
     return out

n = 1000000

t1 = timeit.timeit('convert(bit_list)', 'from __main__ import mult_and_add as convert, bit_list', number=n)
print "mult and add method time is : {} ".format(t1)
t2 = timeit.timeit('convert(bit_list)', 'from __main__ import shifting as convert, bit_list', number=n)
print "shifting method time is : {} ".format(t2)

Result:

mult and add method time is : 1.69138722958 
shifting method time is : 1.94066818592 

Solution 5

how about this:

out = sum([b<<i for i, b in enumerate(my_list)])

or in reverse order:

out = sum([b<<i for i, b in enumerate(my_list[::-1])])
Share:
28,911
ghostmansd
Author by

ghostmansd

Updated on November 15, 2021

Comments

  • ghostmansd
    ghostmansd over 2 years

    I have such list in Python: [1,0,0,0,0,0,0,0]. Can I convert it to integer like as I've typed 0b10000000 (i.e. convert to 128)? I need also to convert sequences like [1,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0] to integers (here it will return 0b1100000010000000, i.e. 259). Length of list is always a multiple of 8, if it is necessary.