Python3 TypeError beheben: unsupported operand type(s) for &: 'bytes' and 'bytes'
English
Deutsch
Problem:
Sie möchten bitweise boolesche Operationen auf bytes()-Arrays in Python durchführen, aber Sie sehen eine Fehlermeldung wie
typeerror_bytes_and_bytes.txt
TypeError: unsupported operand type(s) for &: 'bytes' and 'bytes'oder
typeerror_bytes_or_bytes.txt
TypeError: unsupported operand type(s) for |: 'bytes' and 'bytes'oder
typeerror_bytes_xor_bytes.txt
TypeError: unsupported operand type(s) for ^: 'bytes' and 'bytes'Lösung
Python kann keine bitweisen Operationen direkt auf Byte-Arrays durchführen. Sie können jedoch den Code aus Bitweise boolesche Operationen auf bytes() in Python3 durchführen verwenden:
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")
# Beispielverwendung:
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
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow