Question

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:

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

How do I convert these hex values to ints?

Was it helpful?

Solution

You can use ord() in combination with 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]

OTHER TIPS

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 tuple instead of a list, but I trust you can convert it if you need to.

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top