有点过时,但出于比较的目的,我会在此提供另一个stdlib选项。使用
ctypes模块也很容易实现这一点。
例如:
是否有可能(如何?)表示大小为20的位向量?
我考虑使用24位/ 3字节向量并忽略4个位。
class Simple(ctypes.LittleEndianStructure):
_pack_ = 1
_fields_ = [
('one', ctypes.c_ubyte, 8),
('two', ctypes.c_ubyte, 8),
('three', ctypes.c_ubyte, 8)
]
s = Simple(0, 2, 256)
bytearray(s)
s = Simple(0, 2, 255)
bytearray(s)
class Simple(ctypes.BigEndianStructure):
_pack_ = 1
_fields_ = [
('one', ctypes.c_ubyte, 8),
('two', ctypes.c_ubyte, 8),
('three', ctypes.c_ubyte, 8)
]
s = Simple(0, 2, 256)
bytearray(s)
s = Simple(0, 2, 255)
bytearray(s)
s.two |= 3
bytearray(s)
或者更直接的说法是这样的:
class bit_vector(Structure):
_fields_ = [('bits', c_uint32, 24),
('unused', c_uint32, 8),
]
bv = bit_vector()
bv.bits |= int('000000000000000001000000', 2)
bin(bv.bits)