如何将十六进制字符串转换为整数列表?

12 投票
3 回答
41803 浏览
提问于 2025-04-17 16:23

我有一串很长的十六进制值,它们看起来都差不多,像这样:

'\x00\x00\x00\x01\x00\x00\x00\xff\xff\x00\x00'

这串实际的字符串包含1024帧的波形数据。我想把这些十六进制值转换成一系列整数值,比如:

[0, 0, 0, 1, 0, 0, 0, 255, 255, 0, 0]

我该怎么把这些十六进制值转换成整数呢?

3 个回答

2
In [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

一些时间记录;

9

使用 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)

这样你会得到一个 tuple(元组),而不是 list(列表),不过我相信如果你需要的话,可以把它转换过来。

8

你可以把 ord()map() 一起使用:

>>> s = '\x00\x00\x00\x01\x00\x00\x00\xff\xff\x00\x00'
>>> map(ord, s)
[0, 0, 0, 1, 0, 0, 0, 255, 255, 0, 0]

撰写回答