How to print a signed integer as hexadecimal numbe

2019-02-21 19:25发布

问题:

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

回答1:

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)



回答2:

>>> x = -123
>>> bits = 16
>>> hex((1 << bits) + x)
'0xff85'
>>> bits = 32
>>> hex((1 << bits) + x)
'0xffffff85'


回答3:

Using the bitstring module:

>>> bitstring.BitArray('int:32=-312367').hex
'0xfffb3bd1'


回答4:

Simple

>>> hex((-4) & 0xFF)
'0xfc'


回答5:

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'


回答6:

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'
>>>