Немного устаревший, но я собираюсь оставить здесь еще один вариант 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