hex to signed integer

Tim Roberts timr at probo.com
Wed Jul 16 23:42:56 EDT 2003


Tom Goulet <tomg at em.ca> wrote:

>Hello,
>
>My question basically is:  What is the opposite of the following?
>| "%08X" % -1
>
>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?
>
>This is my current best:
>| struct.unpack("!l", \
>| 	chr(string.atoi(hexbit[0:2], 16)) + \
>| 	chr(string.atoi(hexbit[2:4], 16)) + \
>| 	chr(string.atoi(hexbit[4:6], 16)) + \
>| 	chr(string.atoi(hexbit[6:8], 16)))

(Unrelated note: the blackslashes are unnecessary in this example, since it
is inside a set of parens.)

How slimy is this?

  try:
    temp = int(hexbit,16)
  except:
    temp = int(long(hexbit,16)-2**32)

Equivalently:
  if hexbit[0] < '8':
    temp = int(hexbit,16)
  else:
    temp = int(long(hexbit,16)-2**32)
-- 
- Tim Roberts, timr at probo.com
  Providenza & Boekelheide, Inc.




More information about the Python-list mailing list