hex to signed integer

Bengt Richter bokr at oz.net
Thu Jul 17 17:07:42 CEST 2003


On Wed, 16 Jul 2003 20:13:20 -0600, Steven Taschuk <staschuk at telusplanet.net> wrote:

>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.)
>
Not that this helps 1.5.2-2.4 compatibility, but I
was hoping the signed analogue of 0[xX][0-9A-Fa-f]+
(i.e., [01][xX][0-9A-Fa-f]+  with leading 1 for negatives)
would be available for 2.4.

IMO '-'+hex(abs(x)) really stinks as a hex representation of a negative number x ;-)

 >>> -2**31
 -2147483648L
Oops, is that a wart/buglet BTW?

 >>> int(-2**31)
 -2147483648

 >>> hex(int(-2**31))
 '0x80000000'

with the new format,'1x80000000' would be the way to write int(-2**31) in hex
and '0x80000000' would be +2**31 (which would be internally promoted to long
on 32-bit-integer machines). Other examples

-1 => 1xF # maybe extended (like 0x1 -> 0x0001), i.e., 1xFFFF has same integral value.
-2 => 1xE
-8 => 1x8
-9 => 1x7
-15 => 1x1
-16 => 1x0 # or 1xF0 or 1xFF...F0
-17 => 1xEF

Regards,
Bengt Richter




More information about the Python-list mailing list