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

joshreesjones picture joshreesjones · Feb 19, 2013 · Viewed 29k times · Source

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?

Answer

mgilson picture mgilson · Feb 19, 2013

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.