Cómo crear una matriz de bits en Python?


¿Cómo puedo declarar una matriz de bits de un tamaño muy grande, digamos 6 millones de bits?

4 answers

from bitarray import bitarray

a = bitarray(2**20)

Puedes consultar más información sobre este módulo en http://pypi.python.org/pypi/bitarray /

 32
Author: SJP,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-07-26 12:25:04

El módulo bitstring puede ayudar:

from bitstring import BitArray
a = BitArray(6000000)

Esto tomará menos de un megabyte de memoria, y es fácil establecer, leer, cortar e interpretar bits. A diferencia del módulo bitarray es Python puro, además funciona para Python 3.

Ver la documentación para más detalles.

 23
Author: Scott Griffiths,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-08-11 21:28:53

Obtenga el módulo bitarray usando

pip install bitarray

Entonces, este código creará una matriz de bits de tamaño 6 millones,

from bitarray import bitarray
bit_array = bitarray(6000000)

Puede inicializar todos los bits a cero usando

bit_array.setall(0)

Para establecer un bit en particular, digamos el bit número 25, a 1, haga esto:

bit_array[25]=1   
 5
Author: Tarun,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-05-15 04:33:29

Esta línea convierte bytes a una lista de valores de bits Verdadero/Falso. Puede que no tenga rendimiento para bits de 6M, pero para banderas pequeñas debería estar bien y no necesita dependencias adicionales.

>>> flags = bytes.fromhex(b"beef")
>>> bits =  [flags[i//8] & 1 << i%8 != 0 for i in range(len(flags) * 8)]
>>> print(bits)
[False, True, True, True, True, True, False, True, True, True, True, True, False, True, True, True]
 5
Author: Felix Weis,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-14 02:15:01