Converting hex to int in python

24,080
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.

Share:
24,080
CMDoolittle
Author by

CMDoolittle

Graduate Student in Signal Processing at Portland State University

Updated on November 07, 2021

Comments

  • CMDoolittle
    CMDoolittle over 2 years

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