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}".forma开发者_JAVA百科t(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)
Using the bitstring module:
>>> bitstring.BitArray('int:32=-312367').hex
'0xfffb3bd1'
>>> x = -123
>>> bits = 16
>>> hex((1 << bits) + x)
'0xff85'
>>> bits = 32
>>> hex((1 << bits) + x)
'0xffffff85'
Simple
>>> hex((-4) & 0xFF)
'0xfc'
To treat an integer as a binary value, you bitwise-and it with a mask of the desired bit-length.
For example, for a 4-byte value (32-bit) we mask with 0xffffffff
:
>>> format(-1 & 0xffffffff, "08X")
'FFFFFFFF'
>>> format(1 & 0xffffffff, "08X")
'00000001'
>>> format(123 & 0xffffffff, "08X")
'0000007B'
>>> format(-312367 & 0xffffffff, "08X")
'FFFB3BD1'
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'
>>>
精彩评论