Is there a built-in bitrate similar to std :: bitset from C ++?

I want to use a bitmap in Python, which I could use as a standard set of bits from C ++. Example:

#include<bitset>
int main() {
    std::bitset<100> numBits;
}

However, I do not know if there is something like this in Python, preferably inline.

+2
source share
4 answers

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 // 8 + (1 if lenght % 8  else 0)))
        self.lenght = lenght

    def __setitem__(self, index, value):
        value = int(bool(value)) << (7 - index % 8)
        mask = 0xff ^ (7 - index % 8)
        self.values[index // 8] &= mask
        self.values[index // 8] |= value
    def __getitem__(self, index):
        mask = 1 << (7 - index % 8)
        return bool(self.values[index // 8] & mask)

    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>
+1

, "", :

mybitset = [True, False, False, True, False]

, .

0

list; -: 32- Python 4 "", 64- - 8 . , ( ) Python.

Python array, , list, , , . , Set.

, , Python array PyPI, intbitset

0

int ( long python2). , , .

0

Source: https://habr.com/ru/post/1622081/


All Articles