我有一长串十六进制数值,它们看起来都很相似,像这样:
'\x00\x00\x00\x01\x00\x00\x00\xff\xff\x00\x00'
实际字符串是一个波形的1024帧。我想将这些十六进制值转换为整数值列表,例如:
[0, 0, 0, 1, 0, 0, 0, 255, 255, 0, 0]
我该如何将这些十六进制值转换为整数?
我有一长串十六进制数值,它们看起来都很相似,像这样:
'\x00\x00\x00\x01\x00\x00\x00\xff\xff\x00\x00'
实际字符串是一个波形的1024帧。我想将这些十六进制值转换为整数值列表,例如:
[0, 0, 0, 1, 0, 0, 0, 255, 255, 0, 0]
我该如何将这些十六进制值转换为整数?
使用struct.unpack
函数:
>>> import struct
>>> s = '\x00\x00\x00\x01\x00\x00\x00\xff\xff\x00\x00'
>>> struct.unpack('11B',s)
(0, 0, 0, 1, 0, 0, 0, 255, 255, 0, 0)
struct.unpack()
将字节解释为其他类型。 - Martijn Pietersstruct.unpack
慢了6倍。 当进行一百万次迭代时,struct
需要0.3秒,而map(ord, s)
需要1.8秒。 - Martijn PietersIn [11]: a
Out[11]: '\x00\x00\x00\x01\x00\x00\x00\xff\xff\x00\x00'
In [12]: import array
In [13]: array.array('B', a)
Out[13]: array('B', [0, 0, 0, 1, 0, 0, 0, 255, 255, 0, 0])
以下是一些时间记录:
$ python -m timeit -s 'text = "\x00\x00\x00\x01\x00\x00\x00\xff\xff\x00\x00";' ' map(ord, text)'
1000000 loops, best of 3: 0.775 usec per loop
$ python -m timeit -s 'import array;text = "\x00\x00\x00\x01\x00\x00\x00\xff\xff\x00\x00"' 'array.array("B", text)'
1000000 loops, best of 3: 0.29 usec per loop
$ python -m timeit -s 'import struct; text = "\x00\x00\x00\x01\x00\x00\x00\xff\xff\x00\x00"' 'struct.unpack("11B",text)'
10000000 loops, best of 3: 0.165 usec per loop
struct
仍然更快,但你可以用更少的步骤操作一个 array
并得到一个字节表示。 - Martijn Pieters
\x00
转义用于任何不可打印的ASCII字符。 - Martijn Pieters