I want to invert (flip bits; binary not) all values of a bytearray. I tried this:
for index in xrange(len(data)):
data[index] = ~data[index]
This fails because p.ex. 0 gets -1 and then:
Traceback (most recent call last):
...
data[index] = ~data[index]
ValueError: byte must be in range(0, 256)
You could XOR each value with a bitmask of all ones:
data[index] ^= 0b11111111
Alternatively:
data[index] ^= 0xFF
You need to mask off the higher-order/sign bits that Python creates when you do the bitwise inversion (e.g., in Python, ~0xff
is -256, not the zero that a C programmer would expect.)
>>> b = bytearray((0x00, 0x55, 0xAA, 0xFF))
>>> b
bytearray(b'\x00U\xaa\xff')
>>> for i, v in enumerate(b):
... b[i] = 0xFF & ~v
...
>>> b
bytearray(b'\xff\xaaU\x00')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With