Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting hex to int in python

Tags:

python

hex

ascii

I am reading in 8-bit values from an ADC over USB to my computer. A python script runs on my computer and continuously displays the 8-bit values, which are in hex form. However, when the hex code corresponds to an ASCII code, python will display the ASCII character instead of the raw hex code.

What do I need to do to the incoming data to display just the integer represented by the 8-bits? I don't want it in hex or ASCII. The problem is that the values are coming in with a slash instead of the familiar zero: '\xff' instead of '0xff'. If I go:

int('0xff',16)

the result is 255, but if I try

int('\xff',16)

I get an error: invalid literal for int() with base 16.

Does anyone know of an easy way to handle the \x in the hex code (without resorting to brute force manipulation of the string)?

like image 808
CMDoolittle Avatar asked Nov 06 '13 18:11

CMDoolittle


1 Answers

ord('\xff')

should give you what you want.

\x## represents a single byte or character, if you will, whereas "FF" is a string of two characters that can then be processed with int(my_string,16), but when you have a single character you probably want ord.

You can see this by asking something like len('\xFF') and you will see that it is only a single character.

like image 54
Joran Beasley Avatar answered Nov 17 '22 00:11

Joran Beasley