Search code examples
pythonbytearraysbitcomplement

Python3 Byte Level Bit Operations


Is there a byte type in Python3? I only know there is a bytearray.

What I want is that, there is a byte 0x01, then do the Complement Operator ~ the result will be 0xFE, however when I do the following steps, the result is -2 and -2 can't be added to the bytearray.

>>> data=bytearray([0x01])
>>> data
bytearray(b'\x01')
>>> ~data[0]
-2
>>> data[0]=~data[0]
Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
ValueError: byte must be in range(0, 256)

Solution

  • Python 3 has 2 types dealing with bytes : the bytes type, which is not mutable (analogous to str) and the bytearray with is mutable. If you need to cast an integer to a byte, you simply take the 8 lower order bits with & 0xFF.

    So your last line should be :

    data[0] = ~ data[0] & 0xFF