【问题标题】:Bitwise AND (&) between negative and positive numbers?负数和正数之间的按位与(&)?
【发布时间】:2017-09-04 23:03:37
【问题描述】:

我一直在学习如何使用位操作来添加两个数字,但我在理解 Python 中负数是如何完成的时遇到了问题。例如,如果我尝试& 以下内容:

-0b1111010 (-122) & 0b11011110 (222)

不应该是:

   0b1111010 
& 0b11011110
------------
  0b01011010

因为只有 1 的组合结果为 1?

现在python给0b10000110

当使用python将负数添加到正数时,我找不到任何资源。

【问题讨论】:

  • -0b1111010 是 0b...10000110。
  • Python 中的负整数以2's complement 表示;对负整数的按位运算会产生相应的行为。
  • 你想做什么?通常按位 & 用于逻辑运算,而不是算术运算。 -122 & 222 不会“添加”这些值。它对每一对位执行逻辑“与”操作。要添加值,您可以使用“+”。

标签: python python-3.x bit-manipulation


【解决方案1】:
-122 is  122      0...00001111010
         Flipped  1...11110000101
         +1       1...11110000110 = x

222 is            0...00011011110 = y

x & y             0...00010000110

正如您所演示的那样,这是 Python 显示的内容。

注意,-122 的前导 1 一直到最高有效位。

【讨论】:

    【解决方案2】:

    这是因为 Python 使用 two's complement 二进制有符号整数表示。这是一段代码的 sn-p,其输出显示了实际的字节数据,并说明了为什么你会得到你的结果:

    import math
    
    def bin_format(integer):
        num_bytes = math.ceil(integer.bit_length()/8)  # Number required to represent value.
        ba = integer.to_bytes(num_bytes, 'big', signed=integer<0)
        return ''.join('{:08b}'.format(b) for b in ba) + ' ({:4d})'.format(integer)
    
    print('  ' + bin_format(-122))
    print('& ' + bin_format(222))
    print('=' * 17)
    print('  ' + bin_format(-122 & 222))
    

    输出:

      10000110 (-122)
    & 11011110 ( 222)
    =================
      10000110 ( 134)
    

    【讨论】:

      猜你喜欢
      • 2023-01-12
      • 1970-01-01
      • 2016-01-31
      • 2014-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多