Bitarray and struct pack/unpack round trip

I have this example of packing and unpacking a bitarray:

import struct
from bitarray import bitarray

a = bitarray('11001')
s = struct.pack('s', a.tobytes())
b = bitarray()
b.frombytes(struct.unpack('s', s)[0])
print(a, b, a == b)

which produces:

bitarray('11001') bitarray('11001000') False

What is the way to get a == b? Is there a better way to handle struct.pack() and struct.unpack() for bitarray?

Hmm, it seems to me you don’t have to use struct package at all if the bitarray has got a constructor that accepts bytes-strings and a method that returns it as well :confused:

I use struct because there is more data alongside bitarray I want to pack and unpack. I omitted it, in order to simplify my example.

OK…I’ve just read the documentation. Have you considered using bitarray.util.serialize and bitarray.util.deserialize?

1 Like

Thank you. It works and simplifies code a bit:

a = bitarray('11001')
s = struct.pack('2s', serialize(a))
b = deserialize(struct.unpack('2s', s)[0])
1 Like