ilanschnell / bitarray

efficient arrays of booleans for Python
Other
716 stars 98 forks source link

Phantom bit #210

Closed evglitvin closed 1 year ago

evglitvin commented 1 year ago

Python 3.8, Ubuntu 20, bitarray was installed using pip

The problem is that when padding zeros added there might be trash in it

int.from_bytes(a[:10], byteorder='big') 1617 int.from_bytes(a[:10], byteorder='big') 1616 int.from_bytes(a[:10], byteorder='big') 1616 a[:10] bitarray('0000011001')

ilanschnell commented 1 year ago

Thank you for using bitarray and reporting this issue. What is happening here is that the int method .from_bytes() uses the memoryview of the bitarray object a[:10]. Whenever a[:10] is called, it returns a newly created bitarray object with uninitialized pad bits. Note that the pad bits are not always set to zero. However, when calling bitarray's .tobytes() method, the pad bits will be set to zero. So when calling the following, you will always get the same int value:

int.from_bytes(a[:10].tobytes(), byteorder='big')