如何修复 Python3 TypeError: unsupported operand type(s) for &: bytes and bytes
问题:
你想在 Python 中对 bytes() 数组执行按位布尔操作,但你看到类似这样的错误消息
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'解决方案
Python 无法直接对字节数组执行按位操作。但是,你可以使用如何在 Python3 中对 bytes() 执行按位布尔操作中的代码:
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")
# 示例用法:
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