hex to signed integer

Tom Goulet tomg at em.ca
Wed Jul 16 23:41:54 EDT 2003


Steven Taschuk wrote:

>         return struct.unpack('!i', binascii.unhexlify(s))[0]

Hmm, <unhexlify> is not in <binascii> in Python 1.5.2.

> (This will not be the inverse of '%08x' % n in Python 2.4, when
> '%x' % -1 will produce '-1', but I think it does what you want.)

| >>> print "%08X" % -1294044542
| __main__:1: FutureWarning: %u/%o/%x/%X of negative int will return a \
| 	signed string in Python 2.4 and up

Argh.  Thanks for warning me.

I only want to store thirty-two bits as an integer and input and output
that value of hexadecimal in Python versions 1.5.2 through 2.4, and it's
causing me a lot of grief.  It looks like I'm going to have to resort to
<struct> for both input and output.

>         value = long(s, 16)

A second argument to <long> is not in Python 1.5.2, either.  Using
<atol> from <string> instead works.  Thanks!

-- 
Tom Goulet, tomg at em.ca, D8BAD3BC, http://web.em.ca/~tomg/contact.html




More information about the Python-list mailing list