假设您的十六进制字符串类似于
>>> hex_string = "deadbeef"
将其转换为字符串(Python≤2.7):
>>> hex_data = hex_string.decode("hex")
>>> hex_data
"\xde\xad\xbe\xef"
或从Python 2.7和Python 3.0开始:
>>> bytes.fromhex(hex_string) # Python ≥ 3
b'\xde\xad\xbe\xef'
>>> bytearray.fromhex(hex_string)
bytearray(b'\xde\xad\xbe\xef')
请注意,这bytes
是的不变版本bytearray
。