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.
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).
Try something like this:
a = '\xff'
print int(a.encode('hex'), 16)
255
Edit: sorry, the previous version had a mistake - decode instead of encode. This works.
Edit 2: I actually misread the question, as commenters noted. This may be already obvious but in case someone finds it helpful the regular python list solution would be:
>>> a = '\xff\xfe'
>>> [str(ord(char)) for char in a]
['255', '254']
>>> ' '.join([str(ord(char)) for char in a])
'255 254'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With