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

假装没事ソ 提交于 2020-01-21 10:56:29

问题


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


来源:https://stackoverflow.com/questions/3235515/how-to-print-a-signed-integer-as-hexadecimal-number-in-twos-complement-with-pyt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!