我有一个长十六进制字符串,表示一系列不同类型的值。我需要将这个十六进制字符串转换为字节或bytearray,这样我就可以从原始数据中提取每个值。我该怎么做呢?
例如,字符串“ab”应该转换为字节b“\xab”或等效的字节数组。再例如:
>>> # what to use in place of `convert` here?
>>> convert("8e71c61de6a2321336184f813379ec6bf4a3fb79e63cd12b")
b'\x8eq\xc6\x1d\xe6\xa22\x136\x18O\x813y\xeck\xf4\xa3\xfby\xe6<\xd1+'
假设你的十六进制字符串是这样的
>>> hex_string = "deadbeef"
将其转换为bytearray (Python 3和2.7):
>>> bytearray.fromhex(hex_string)
bytearray(b'\xde\xad\xbe\xef')
将其转换为字节对象(Python 3):
>>> bytes.fromhex(hex_string)
b'\xde\xad\xbe\xef'
注意,bytes是bytearray的不可变版本。
将其转换为字符串(Python≤2.7):
>>> hex_data = hex_string.decode("hex")
>>> hex_data
"\xde\xad\xbe\xef"