【问题标题】:In python3 I can't get -1 to print 0xFF. Is there a way?在 python3 中,我无法得到 -1 来打印 0xFF。有办法吗?
【发布时间】:2021-07-25 17:49:09
【问题描述】:

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

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

【问题讨论】:

    标签: python-3.x printing raspberry-pi


    【解决方案1】:

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

    将数字显式包装到所需范围:

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

    【讨论】:

      【解决方案2】:

      你可以试试这样的:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-04-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-09
        • 2017-04-21
        • 2022-12-22
        • 1970-01-01
        相关资源
        最近更新 更多