Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

binary invert values of bytearray

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)
like image 435
Knut Avatar asked Feb 09 '23 02:02

Knut


2 Answers

You could XOR each value with a bitmask of all ones:

data[index] ^= 0b11111111

Alternatively:

data[index] ^= 0xFF
like image 130
Kevin Avatar answered Feb 10 '23 15:02

Kevin


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')
like image 29
bgporter Avatar answered Feb 10 '23 16:02

bgporter