少し古いですが、比較のために別の 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) # bytearray(b'\x00\x02\x00')
s = Simple(0, 2, 255)
bytearray(s) # bytearray(b'\x00\x02\xff')
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) # bytearray(b'\x00\x02\x00')
s = Simple(0, 2, 255)
bytearray(s) # bytearray(b'\x00\x02\xff')
s.two |= 3
bytearray(s) # bytearray(b'\x00\x03\xff')
または、次のようなより簡単なもの:
class bit_vector(Structure):
_fields_ = [('bits', c_uint32, 24),
('unused', c_uint32, 8),
]
bv = bit_vector()
# turn on the 18th bit -- being explicit just to demo it
bv.bits |= int('000000000000000001000000', 2)
bin(bv.bits) # 0b1000000