在 python3 中,我无法得到 -1 来打印 0xFF。有办法吗?

In python3 I can't get -1 to print 0xFF. Is there a way?

如何让下面的各种输出结果为 0xFF 或 0xFFFF?

>>> key=-1
>>> print(key)
-1
>>> print(hex(key))
-0x1
>>> print("Key={:4X}".format(key))
Key=  -1
>>>

Python 整数是任意精度 – -1 不能“环绕”到最大值。

明确将数字换行到所需范围内:

>>> key = -1
>>> hex(key % 256)    # restrict to range 0-255
0xff
>>> hex(key % 65536)  # restrict to range 0-65535
0xffff

您可以尝试类似的方法:

>>> def do_what_you_want(number, length):
...     print(hex(number+(1<<(length*4))))
...
>>> do_what_you_want(-1, 2)
0xff
>>> do_what_you_want(-1, 4)
0xffff