10

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

2
  • 1
    int(r'\xff'[2:], 16) would work. Nov 6, 2013 at 18:35
  • he is getting the '\xff' from somewhere else he does not have the option to make it a literal string I dont think Nov 6, 2013 at 18:39

1 Answer 1

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.