Search code examples
pythonintegerhexsignedtwos-complement

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


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..."


Solution

  • 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)