How to fix Python3 TypeError: unsupported operand type(s) for &: 'bytes' and 'bytes'

Problem:

You want to perform bitwise boolean operations on bytes() arrays in Python, but you see an error message like

typeerror_bytes_and_bytes.txt
TypeError: unsupported operand type(s) for &: 'bytes' and 'bytes'

or

typeerror_bytes_or_bytes.txt
TypeError: unsupported operand type(s) for |: 'bytes' and 'bytes'

or

typeerror_bytes_xor_bytes.txt
TypeError: unsupported operand type(s) for ^: 'bytes' and 'bytes'

Solution

Python can’t perform bitwise operations directly on byte arrays. However, you can use the code from How to perform bitwise boolean operations on bytes() in Python3:

bitwise_bytes_ops.py
def bitwise_and_bytes(a, b):
    result_int = int.from_bytes(a, byteorder="big") & int.from_bytes(b, byteorder="big")
    return result_int.to_bytes(max(len(a), len(b)), byteorder="big")

def bitwise_or_bytes(a, b):
    result_int = int.from_bytes(a, byteorder="big") | int.from_bytes(b, byteorder="big")
    return result_int.to_bytes(max(len(a), len(b)), byteorder="big")

def bitwise_xor_bytes(a, b):
    result_int = int.from_bytes(a, byteorder="big") ^ int.from_bytes(b, byteorder="big")
    return result_int.to_bytes(max(len(a), len(b)), byteorder="big")

# Example usage:

a = bytes([0x00, 0x01, 0x02, 0x03])
b = bytes([0x03, 0x02, 0x01, 0xff])

print(bitwise_and_bytes(a, b)) # b'\\x00\\x00\\x00\\x03'
print(bitwise_or_bytes(a, b)) # b'\\x03\\x03\\x03\\xff'
print(bitwise_xor_bytes(a, b)) # b'\\x03\\x03\\x03\\xfc'

Check out similar posts by category: Python