2017-02-26 5 views
5

Supposons que je définir des BitArray en python utilisant le code suivant:Comment convertir BitArray à un entier en python

from bitarray import bitarray 
d=bitarray('0'*30) 
d[5]=1 

Comment puis-je convertir d à sa représentation entière? En outre, comment puis-je effectuer des manipulations telles que d&(d+1) avec bitarrays?

+1

Cela ressemble à Python 3.2+, vous pouvez dire 'int.from_bytes (d.tobytes)', mais je n'ai pas le moyen de vérifier cela. Vous pourriez avoir à jouer avec l'endian-ness du «bitarray». – Gene

Répondre

5

Pour convertir un bitarray à sa forme entière, vous pouvez utiliser le module struct:

Code:

from bitarray import bitarray 
import struct 

d = bitarray('0' * 30, endian='little') 

d[5] = 1 
print(struct.unpack("<L", d)[0]) 

d[6] = 1 
print(struct.unpack("<L", d)[0]) 

Sorties:

32 
96 
3
from bitarray import bitarray 
d=bitarray('0'*30) 
d[5]=1 

i = 0 
for bit in d: 
    i = (i << 1) | bit 

print i 

sortie: 16777216.