从整数创建 python 位数组 - 奇怪的结果!
我刚刚开始在 python 中使用 bitarray 包,并尝试从整数创建 bitarray 给了我非常令人困惑的结果:
>>> import bitarray
>>> bitarray.bitarray(5)
bitarray('01000')
>>> bitarray.bitarray(5)
bitarray('00010')
>>> bitarray.bitarray(5)
bitarray('00100')
>>> bitarray.bitarray(5)
bitarray('00110')
有谁知道为什么会发生这种情况?
另外:从 int 生成位数组的更好方法是什么?这可行,但字符串转换似乎是一种奇怪的方法...
>>> bitarray.bitarray(bin(5)[2:])
bitarray('101')
编辑:我最终切换到bitstring,它确实有一个从整数获取位串的简单方法:
>>> bitstring.BitArray(uint=5,length=6)
BitArray('0b000101')
I'm just starting to use the bitarray package in python, and trying to make a bitarray from an integer gives me really confusing results:
>>> import bitarray
>>> bitarray.bitarray(5)
bitarray('01000')
>>> bitarray.bitarray(5)
bitarray('00010')
>>> bitarray.bitarray(5)
bitarray('00100')
>>> bitarray.bitarray(5)
bitarray('00110')
Does anyone have any idea why this would be happening??
Also: what would be a better way of making a bitarray from an int? This works, but string conversion seems like a strange way to do it...
>>> bitarray.bitarray(bin(5)[2:])
bitarray('101')
Edit: I ended up switching to bitstring, which does have an easy method of getting bitstrings from ints:
>>> bitstring.BitArray(uint=5,length=6)
BitArray('0b000101')
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
来自“bitarray.util 模块中定义的函数:”下的项目页面。
From the project page under "Functions defined in bitarray.util module:".
bitarray.bitarray(n)
创建一个长度为n
的未初始化数组。就从整数创建而言,
bitarray
似乎并不特别适合于此,因此您必须使用pack/unpack
或循环遍历各个位来设置它们。bitarray.bitarray(n)
creates an uninitialized array of lengthn
.As far as creating from an integer,
bitarray
doesn't appear to be particularly geared towards that, so you'll either have to usepack/unpack
or loop over the individual bits to set them.