Converting a hex string to an integer

Fredrik Lundh effbot at telia.com
Fri Mar 31 05:27:01 EST 2000


Peter Koren <pkoren at hex.net> wrote:
> > How can I convert a hex string like '0xab' to an integer? Here is what
> >>> def printint(x):
> ...     print x
> ...
> >>> printint(0xab)
> 171

usage:  if given a hexadecimal string, use your editor
to write a python module that looks exactly like this:

    from peter import printint
    printint(<string>)

where <string> is replaced with the string in question
(without the quotes).  run the script, and note the
output value.

then edit your original script, replacing the hexadecimal
string with the value printed by that other script.

other great tips:

if you get hexadecimal strings from files or other data-
sources, you can use input instead:

    value = string.strip(file.readline())
    if value[:2] == "0x":
        print "please type in the following string:", value
        value = input(value)

as an added bonus, this allows the user to adjust the
value if necessary.

see also: string.atoi

</F>





More information about the Python-list mailing list