Hex to int conversion error

Patrick Maupin pmaupin at speakeasy.net
Tue Oct 28 01:08:53 EST 2003


"Adam Ritter" <temporary_addr at hotmail.com> wrote in message news:<mailman.137.1067269508.702.python-list at python.org>...
> When I try to convert an 8 digit hex number to an integer, I get a 
> ValueError.  Why doesn't it convert back correctly?  I have the string 
> '0xdeadbeaf' stored in a textbox and I would like it's integer value.  I 
> would convert it to a long, but I need to pack it to send as a 4 byte 
> integer through a socket to a C program.  Any ideas?
> 
> >>>int(0xdeadbeaf)
>  -559038801
> >>>int(hex(int(0xdeadbeaf)) ,16)
> Traceback (most recent call last):
>    File "<stdin>", line 1, in ?
> ValueError: int() literal too large: 0xdeadbeaf

Unfortunately, that's what you get in 2.2, which is _different_
than what you'll get in 2.3, which is _still_ _different_ than
what you'll get in 2.4.  This whole "deal with machine words"
is not really directly supported -- even using struct as
one previous poster suggested can lead to trouble.

The solution is to write your own 'hex' and 'int' functions.
The following code **should** work under 2.2, 2.3, and 2.4,
although it will give FutureWarnings under 2.3  (you can shut
them off using the filter in the warnings module).

import sys


def short(what,offset=sys.maxint+1,modulus=(sys.maxint+1)*2):
    """short(n) converts a long into an int, ignoring high-order bits"""
    return int(((what + offset) % modulus) - offset)

def poslong(what,modulus=(sys.maxint+1)*2):
    """poslong(n) takes an int and returns a long with the same bit
       pattern in the lower bits, and zeros in the upper bits.  (Guaranteed
       positive result)"""
    return what % modulus

def hexshort(what):
    """hexshort(n) returns a hex number without any annoying minus sign in 2.4"""
    return '0x%x' % poslong(what)    

print short(0xdeadbeef)
print hexshort(short(0xdeadbeef))
print long(hexshort(short(0xdeadbeef)),16)
print short(long(hexshort(short(0xdeadbeef)),16))

Hope this helps.

Pat




More information about the Python-list mailing list