Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bits list to integer in Python

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.

like image 632
ghostmansd Avatar asked Sep 17 '12 14:09

ghostmansd


People also ask

How do you convert a list of data to integers in Python?

Use int() function to Convert list to int in Python. This method with a list comprehension returns one integer value that combines all elements of the list.

How many bits is an integer Python?

To be safe, Python allocates a fixed number of bytes of space in memory for each variable of a normal integer type, which is known as int in Python. Typically, an integer occupies four bytes, or 32 bits.

How do you convert a list of strings to numbers in Python?

The most Pythonic way to convert a list of strings to a list of ints is to use the list comprehension [int(x) for x in strings] . It iterates over all elements in the list and converts each list element x to an integer value using the int(x) built-in function.


1 Answers

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 
like image 74
Martijn Pieters Avatar answered Sep 22 '22 01:09

Martijn Pieters