【问题标题】:How do I convert a string of hexadecimal values to a list of integers?如何将一串十六进制值转换为整数列表?
【发布时间】:2013-02-04 08:59:34
【问题描述】:

我有一长串十六进制值,看起来都与此类似:

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

实际的字符串是 1024 帧的波形。我想将这些十六进制值转换为整数值列表,例如:

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

如何将这些十六进制值转换为整数?

【问题讨论】:

  • 您有一个字节字符串,python 在打印时会为您转换为字符串文字表示。 \x00 转义符用于任何不是可打印 ASCII 字符的字节。

标签: python audio hex signal-processing waveform


【解决方案1】:

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

【讨论】:

  • 不是最好的方法,没有struct.unpack() 可用并且也能够将字节解释为其他类型。
  • @MartijnPieters -- 但是解决这个非常有限的问题的聪明方法......它让我微笑。
  • 这个解决方案比 struct.unpack 慢 6 倍,顺便说一句.. struct 需要 0.3 秒进行一百万次迭代,而 map(ord, s) 需要 1.8 秒。
  • @MartijnPieters 相对而言,当然.. 但是相对于脚本中发生的其他所有事情,它需要多少 CPU 时间?同样,代码和然后优化。
  • @cdhowie:但是事先知道什么会更快,你就成功了一半。 Stack Overflow 让您有机会了解您对给定操作的选项;通过在此处的答案中添加时间信息,您可以做出更明智的选择如果需要优化,则不必自己去优化。
【解决方案2】:

使用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,但我相信您可以根据需要进行转换。

【讨论】:

    【解决方案3】:
    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
    

    【讨论】:

    • 不错;一百万次迭代需要 0.665 秒。 struct 仍然更快,但您可以操作 array 并以更少的步骤获取字节表示。
    • @MartijnPieters - 来自大师的赞美! Guido 不会错optimization anectode
    猜你喜欢
    • 2011-08-04
    • 2010-10-16
    • 2017-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-29
    相关资源
    最近更新 更多