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..."
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..."
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)
See if this answer to a related question is what you're looking for: http://stackoverflow.com/questions/1604464/twos-complement-in-python/1605553#1605553
Using the bitstring module:
>>> bitstring.Bits('int:32=-312367').hex
'0xfffb3bd1'
>>> x=123
>>> bits=16
>>> hex((1<<bits)-x)
'0xff85'
>>> bits=32
>>> hex((1<<bits)-x)
'0xffffff85'
The struct
module performs conversions between Python values and C structs represented as Python bytes objects. The packed bytes object offers access to individual byte values.
This can be used to display the underlying (C) integer representation.
>>> packed = struct.pack('>i',i) # big-endian integer
>>> type(packed)
<class 'bytes'>
>>> packed
b'\xff\xfb;\xd1'
>>> "%X%X%X%X" % tuple(packed)
'FFFB3BD1'
>>>