String to Hex

Peter Otten __peter__ at web.de
Wed Oct 27 07:09:11 EDT 2004


Michael Foord wrote:

> How do you safely turn an arbitrarily long signed hex string into a
> long integer ?
> e.g. -0x55aff8080000
> 
> When treating them as hex literals I'm getting future warnings that
> from 2.4 hex values greater than sys.maxint will always return
> positive values. I've had to treat them as strings and write a
> function to turn them into longs a character at a time ! I couldn't
> find a built in function that would do this for me.

One (fragile) way to avoid that Python 2.3 interprets
0x80000000...0xffffffff (on 32-bit systems) as negative integers is to add
an explicit sign:

$ python -c"print int('0xffffffff', 0)"
-c:1: FutureWarning: int('0...', 0): sign will change in Python 2.4
-1
$ python -c"print int('+0xffffffff', 0)"
4294967295
$ python -c"print int('-0xffffffff', 0)"
-4294967295

Peter




More information about the Python-list mailing list