How to print a signed integer as hexadecimal number in two's complement with python?

none picture none · Jul 13, 2010 · Viewed 13.6k times · Source

I have a negative integer (4 bytes) of which I would like to have the hexadecimal form of its two's complement representation.

>>> i = int("-312367")
>>> "{0}".format(i)
'-312367'
>>> "{0:x}".format(i)
'-4c42f'

But I would like to see "FF..."

Answer

adamk picture adamk · Jul 13, 2010

Here's a way (for 16 bit numbers):

>>> x=-123
>>> hex(((abs(x) ^ 0xffff) + 1) & 0xffff)
'0xff85'

(Might not be the most elegant way, though)