如何正确编写和读取BitArray对象?
我有一个问题。我尝试将我的bitarray
对象保存到文件中。之后,我想阅读它并获得相同的bitarray
对象我之前保存的内容。但是结果与输入不同。
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))
输出:
00000000001111 14
0000000000111100 16
我现在看到我的对象是 2字节表示。但是我想获得 14位我保存了。您有什么想法可以做对吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这不是一个很好的解决方案,但确实可以摆脱右边的0。
您可以跳过逆转和正确的偏移
b
,但是您必须创建一个动态系统,该系统确切知道要移动多少位。另一个解决方案是首先简单地使用8位。您在这里删除1至7位在这里节省了什么?您不会保存文件中的任何内容。无论如何,这些碎片都将被填充。This isn't a great solution, but it does get rid of the 0's on the right.
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.这不是一个很好的解决方案,而是解决方案)
我只包含数量的零,它将在保存/读取文件后出现,然后轻松删除这些零
It's eather not a great solution, but it's a solution)
I just contain number of zeroes, which will appear after save/read in files and then easy delete those zeroes