如何在 Python3 中对 bytes() 执行按位布尔操作
在 Python3.2+ 中对 bytes() 实例执行按位操作很简单但不直接:
- 使用
int.from_bytes(...)获取表示字节数组的整数 - 使用该整数执行按位操作
- 使用
result.to_bytes(...)将整数转换回bytes()数组
注意要使结果有意义,你需要确保两个 bytes() 实例具有相同的长度。
Python 代码:
bitwise_bytes_utils.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")示例用法:
bitwise_bytes_example.py
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