Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 950
John von N. Avatar asked Feb 28 '26 03:02

John von N.


2 Answers

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).

like image 190
Sven Marnach Avatar answered Mar 01 '26 15:03

Sven Marnach


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'
like image 27
Eduardo Ivanec Avatar answered Mar 01 '26 17:03

Eduardo Ivanec



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!