Hex to int conversion error

Peter Hansen peter at engcorp.com
Mon Oct 27 11:52:54 EST 2003


Adam Ritter wrote:
> 
> 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

If your description above, that you "need to pack it to send as a 
4 byte integer", is correct, you should need only the struct module:

   struct.pack('L', long('deadbeef', 16))

The value 0xdeadbeef is negative if treated as an int (since ints are
signed in Python), so you can't treat it as an unsigned int.  Instead,
since in effect you want to treat all values as unsigned, use long()
and the "L" (unsigned long) operand to struct.pack.  Note that if you
then give it a negative long, you'll still get an OverflowError,
this time from struct.pack itself.

-Peter




More information about the Python-list mailing list