Python 如何将十六进制值字符串转换为整数列表?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14961562/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I convert a string of hexadecimal values to a list of integers?
提问by joshreesjones
I have a long string of hexadecimal values that all looks similar to this:
我有一长串十六进制值,看起来都与此类似:
'\x00\x00\x00\x01\x00\x00\x00\xff\xff\x00\x00'
The actual string is 1024 frames of a waveform. I want to convert these hexadecimal values to a list of integer values, such as:
实际字符串是一个波形的 1024 帧。我想将这些十六进制值转换为整数值列表,例如:
[0, 0, 0, 1, 0, 0, 0, 255, 255, 0, 0]
How do I convert these hex values to ints?
如何将这些十六进制值转换为整数?
采纳答案by cdhowie
回答by mgilson
use 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)
This gives you a tupleinstead of a list, but I trust you can convert it if you need to.
这给你 atuple而不是 a list,但我相信你可以在需要时转换它。
回答by Fredrik Pihl
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])
Some timings;
一些时间;
$ 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

