[英]How to pack & unpack 64 bits of data?
我有一个64位数据结构,如下所示:
HHHHHHHHHHHHHHHHGGGGGGGGGGGGFFFEEEEDDDDCCCCCCCCCCCCBAAAAAAAAAAAA
A:12位(无符号)
B:1位
C:12位(无符号)
D:4位(无符号)
E:4位(无符号)
F:3位(无符号)
G:12位(无符号)
H:16位(无符号)
使用Python,我试图确定我应该使用哪个模块(最好是本机Python 3.x)。 我正在查看BitVector,但无法弄清楚某些事情。
为了易于使用,我希望能够执行以下操作:
# To set the `A` bits, use a mapped mask 'objectId'
bv = BitVector(size=64)
bv['objectId'] = 1
我不确定BitVector是否确实按照我想要的方式工作。 无论我最终实现什么模块,数据结构都将封装在一个类中,该类通过属性getter / setter对该结构进行读写。
我还将对某些位值使用常量(或枚举),并且能够使用类似以下的方式设置映射的掩码会很方便:
# To set the 'B' bit, use the constant flag to set the mapped mask 'visibility'
bv['visibility'] = PUBLIC
print(bv['visibility']) # output: 1
# To set the 'G' bits, us a mapped mask 'imageId'
bv['imageId'] = 238
3.x中是否有Python模块可以帮助我实现这一目标? 如果BitVector能够(或应该)起作用,将感谢一些有用的提示(例如示例)。 似乎BitVector希望将所有内容强制为8位格式,这对于我的应用程序(IMHO)而言并不理想。
基于使用位数组的建议,我提出了以下两种实用方法的实现:
def test_bitvector_set_block_id_slice(self):
bv = bitvector(VECTOR_SIZE)
bv.setall(False)
print("BitVector[{len}]: {bv}".format(len=bv.length(),
bv=bv.to01()))
print("set block id: current {bid} --> {nbid}".format(bid=bv[52:VECTOR_SIZE].to01(),
nbid=inttobitvector(12, 1).to01()))
# set blockVector.blockId (last 12 bits)
bv[52:VECTOR_SIZE] = inttobitvector(12, 1)
block_id = bv[52:VECTOR_SIZE]
self.assertTrue(bitvectortoint(block_id) == 1)
print("BitVector[{len}] set block id: {bin} [{val}]".format(len=bv.length(),
bin=block_id.to01(),
val=bitvectortoint(block_id)))
print("BitVector[{len}]: {bv}".format(len=bv.length(),
bv=bv.to01()))
print()
# utility methods
def bitvectortoint(bitvec):
out = 0
for bit in bitvec:
out = (out << 1) | bit
return out
def inttobitvector(size, n):
bits = "{bits}".format(bits="{0:0{size}b}".format(n,
size=size))
print("int[{n}] --> binary: {bits}".format(n=n,
bits=bits))
return bitvector(bits)
输出如下:
BitVector[64]: 0000000000000000000000000000000000000000000000000000000000000000
int[1] --> binary: 000000000001
set block id: current 000000000000 --> 000000000001
int[1] --> binary: 000000000001
BitVector[64] set block id: 000000000001 [1]
BitVector[64]: 0000000000000000000000000000000000000000000000000000000000000001
如果对实用程序方法有所改进,我很乐意听取一些建议。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.