Search code examples
pythonnumpypyglet

Converting a hexadecimal character to an int in Python


I'm using the graphics library Pyglet to do some drawing and want to get the resulting image out as a Python list (so I can convert it to a NumPy array).

Pyglet gives me a string of hex characters, like this: '\xff' (indicating a value of 255 at one pixel). How can I convert such a string to an int?

I've tried int('\xff', 16), but that doesn't work. Note that according to the documentation, '\xnn' is escaped and encoded as a hexedecimal char, but it doesn't tell me how to convert that to an int.


Solution

  • To get a NumPy array straight from a Python string, you can use

    s = "\xff\x03"
    a = numpy.frombuffer(s, numpy.uint8)
    

    To get a list you can use

    a =  map(ord, s)
    

    An alternative to a list in Python 2.6 or above is to use bytesarray(s).