hex to signed integer

Steven Taschuk staschuk at telusplanet.net
Wed Jul 16 22:13:20 EDT 2003


Quoth Tom Goulet:
> My question basically is:  What is the opposite of the following?
> | "%08X" % -1

Here's one way, very like what you already have:

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

(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.)

Another approach:

    def hex2signed(s):
        value = long(s, 16)
        if value > sys.maxint:
            value = value - 2L*sys.maxint - 2
        assert -sys.maxint-1 <= value <= sys.maxint
        return int(value)

-- 
Steven Taschuk     staschuk at telusplanet.net
"Please don't damage the horticulturalist."
         -- _Little Shop of Horrors_ (1960)





More information about the Python-list mailing list