繁体   English   中英

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

[英]How do I convert a string of hexadecimal values to a list of integers?

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

'\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)

这给你一个tuple而不是list ,但我相信如果你需要你可以转换它。

您可以将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]
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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM