hex to signed integer

David Bolen db3l at fitlinxx.com
Thu Jul 17 18:33:22 EDT 2003


Tom Goulet <tomg at em.ca> writes:

> Tim Roberts wrote:
> > Tom Goulet <tomg at em.ca> wrote:
>  
> >>I want to convert a string of hexadecimal characters to the signed
> >>integer they would have been before the <print> statement converted
> >>them.  How do I do this in such a way that is compatible with Python
> >>versions 1.5.2 through 2.4, and not machine-dependent?
> 
> >   if hexbit[0] < '8':
> >     temp = int(hexbit,16)
> >   else:
> >     temp = int(long(hexbit,16)-2**32)
> 
> The <int> function takes only one argument in Python 1.5.2.

Yes, the base argument was added in later around Python 2.0.

An equivalent operation to int(value,base) in Python 1.5.2 and any of
the later versions (at least through 2.3 - 2.4 doesn't exist yet)
would be the string.atoi(value,base) function.

However, as indicated by the above code, both int() and string.atoi()
limit their result to a signed integer, so depending on the
hexadecimal string it might overflow and result in an exception.  So
for any sized hexadecimal string, use string.atol(value,base) instead.

For example:

    Python 2.2.3 (#42, May 30 2003, 18:12:08) [MSC 32 bit (Intel)] on win32
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import string
    >>> print string.atoi('20',16)
    32
    >>> print string.atoi('FFFFFFFF',16)
    Traceback (most recent call last):
      File "<stdin>", line 1, in ?
      File "c:\Python\2.2\lib\string.py", line 225, in atoi
        return _int(s, base)
    ValueError: int() literal too large: FFFFFFFF
    >>> print string.atol('FFFFFFFF',16)
    4294967295
    >>> print string.atol('%08X' % -1,16)
    4294967295
    >>> 

One note - if you end up converting the result of string.atol() with
str(), under Python 1.5.2 it will have a trailing "L" but will not
have that under any later Python release.  Converting it to a string
with repr() will have the trailing "L" under all Python releases.

-- David




More information about the Python-list mailing list