There is nothing built in for this. If you need such a data structure to have the correct byte output with the correct bits set, for example, for a network protocol, binary file structure or hardware control, ordering a list of True and False values for a sequence of Bytes is easily feasible.
, bytearray. , , ++, (, ) - Python True False ( 0 1 ) , .
, True False, , , , , :
a = [True, True, False, False, False, True, ...]
with open("myfile.bin", "wb" as file):
for i, value in enumerate(a):
if not i % 8:
if i:
file.write(byte)
byte = 0
byte <<= 1
byte |= value
if i % 8:
byte <<= (8 - i % 8)
file.write(byte)
, bytearray - reset - :
class BitArray(object):
def __init__(self, lenght):
self.values = bytearray(b"\x00" * (lenght
self.lenght = lenght
def __setitem__(self, index, value):
value = int(bool(value)) << (7 - index % 8)
mask = 0xff ^ (7 - index % 8)
self.values[index
self.values[index
def __getitem__(self, index):
mask = 1 << (7 - index % 8)
return bool(self.values[index
def __len__(self):
return self.lenght
def __repr__(self):
return "<{}>".format(", ".join("{:d}".format(value) for value in self))
, , , . , :
In [50]: a = BitArray(16)
In [51]: a[0] = 1
In [52]: a[15] = 1
In [53]: a
Out[53]: <1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1>