Hex to int conversion error
Batista, Facundo
FBatista at uniFON.com.ar
Mon Oct 27 11:30: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
Divide and conquer:
>>> a = int(0xdeadbeaf)
>>> a
-559038801
>>> b = hex(a)
>>> b
'0xdeadbeaf'
>>> b[2:]
'deadbeaf'
>>> int(b[2:], 16)
3735928495L
>>>
Take note of the signs, and read the following warning:
__main__:1: FutureWarning: hex()/oct() of negative int will return a signed
string in Python 2.4 and up
. Facundo
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
ADVERTENCIA
La información contenida en este mensaje y cualquier archivo anexo al mismo,
son para uso exclusivo del destinatario y pueden contener información
confidencial o propietaria, cuya divulgación es sancionada por la ley.
Si Ud. No es uno de los destinatarios consignados o la persona responsable
de hacer llegar este mensaje a los destinatarios consignados, no está
autorizado a divulgar, copiar, distribuir o retener información (o parte de
ella) contenida en este mensaje. Por favor notifíquenos respondiendo al
remitente, borre el mensaje original y borre las copias (impresas o grabadas
en cualquier medio magnético) que pueda haber realizado del mismo.
Todas las opiniones contenidas en este mail son propias del autor del
mensaje y no necesariamente coinciden con las de Telefónica Comunicaciones
Personales S.A. o alguna empresa asociada.
Los mensajes electrónicos pueden ser alterados, motivo por el cual
Telefónica Comunicaciones Personales S.A. no aceptará ninguna obligación
cualquiera sea el resultante de este mensaje.
Muchas Gracias.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20031027/1312dddf/attachment.html>
More information about the Python-list
mailing list