简体   繁体   English

如何使用python以二进制补码打印有符号整数作为十六进制数?

[英]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. 我有一个负整数(4个字节),我希望它的二进制补码表示形式的十六进制形式。

>>> i = int("-312367")
>>> "{0}".format(i)
'-312367'
>>> "{0:x}".format(i)
'-4c42f'

But I would like to see "FF..." 但我想看看“FF ......”

Here's a way (for 16 bit numbers): 这是一种方式(对于16位数字):

>>> x=-123
>>> hex(((abs(x) ^ 0xffff) + 1) & 0xffff)
'0xff85'

(Might not be the most elegant way, though) (但可能不是最优雅的方式)

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

Using the bitstring module: 使用bitstring模块:

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

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 : 例如,对于4字节值(32位),我们使用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. struct模块执行Python值和表示为Python字节对象的C结构之间的转换。 The packed bytes object offers access to individual byte values. 压缩字节对象提供对单个字节值的访问。 This can be used to display the underlying (C) integer representation. 这可用于显示基础(C)整数表示。

>>> packed = struct.pack('>i',i) # big-endian integer
>>> type(packed)
<class 'bytes'>
>>> packed
b'\xff\xfb;\xd1'
>>> "%X%X%X%X" % tuple(packed)
'FFFB3BD1'
>>> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM