'How to properly write and read BitArray objects?
I have an issue. I tryed to save my BitArray object into file. After that I want to read it and get the same BitArray object what I saved earlier. But result is not same with input.
from bitarray import bitarray
a = bitarray()
a += bitarray('{0:014b}'.format(15))
print(a.to01(), len(a))
with open('j.j', 'wb') as file:
a.tofile(file)
b = bitarray()
with open('j.j', 'rb') as file:
b.fromfile(file)
print(b.to01(), len(b))
Output:
00000000001111 14
0000000000111100 16
I see my object now is 2-byte representation. But I want to get 14-bit I saved. Do you have any ideas to make it right?
Solution 1:[1]
This isn't a great solution, but it does get rid of the 0's on the right.
from bitarray import bitarray
a = bitarray('{0:014b}'.format(15))
print(a.to01(), len(a)) #00000000001111 14
with open('j.j', 'wb') as file:
a.reverse()
a.tofile(file)
b = bitarray()
with open('j.j', 'rb') as file:
b.fromfile(file)
b.reverse()
print(b.to01(), len(b)) #0000000000001111 16
You could skip the reversals and just right shift b, but you would have to create a dynamic system that knows exactly how many bits to shift by. Another solution is to simply use bits in multiples of 8 in the first place. What are you saving here by removing 1 to 7 bits? You aren't saving anything in the file. Those bits will be padded regardless.
Solution 2:[2]
It's eather not a great solution, but it's a solution)
def encode():
encoded_bits = bitarray()
...
encoded_bits += bitarray('000') # 48:51 slice
zeroes_at_the_end = 8 - len(encoded_bits) % 8
if zeroes_at_the_end < 8:
encoded_bits[48:51] = bitarray('{0:03b}'.format(zeroes_at_the_end))
def decode(bites_sequence):
zeroes_at_the_end = ba2int(bites_sequence[48:51])
if zeroes_at_the_end != 0:
del bites_sequence[-zeroes_at_the_end:]
I just contain number of zeroes, which will appear after save/read in files and then easy delete those zeroes
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | kanvull |
