负数和正数之间的按位和(&)?

时间:2017-09-04 23:03:38

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

我一直在学习使用位操作添加两个数字,我在理解如何在Python中使用负数来解决问题。例如,如果我尝试-0b1111010 (-122) & 0b11011110 (222) 以下内容:

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

不应该是:

0b10000110

因为只有1的组合会产生1?

现在python提供SO301000result = context.SO301000Submit( new Command[] { new Value { Value = "SO", LinkedCommand = SO301000.OrderSummary.OrderType }, new Value { Value = ordNum, LinkedCommand = SO301000.OrderSummary.OrderNbr }, //popup window new Value { Value = "OK", LinkedCommand = SO301000.AddInvoiceDetails.DialogAnswer, Commit = true }, new Value { Value = "Invoice", LinkedCommand = SO301000.AddInvoiceDetailsDocType.DocType }, new Value { Value = "C0000155", LinkedCommand = SO301000.AddInvoiceDetailsDocType.RefNbr, Commit = true }, //HERE Error: One or more rows failed to validate new Key { Value = "='CPU00004'", FieldName = SO301000.AddInvoiceDetails.InventoryID_, ObjectName = SO301000.AddInvoiceDetails.InventoryID.ObjectName }, new Value { Value = "True", LinkedCommand = SO301000.AddInvoiceDetails.Selected, Commit = true }, SO301000.Actions.AddInvoice SO301000.Actions.Save } );

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

2 个答案:

答案 0 :(得分:2)

-122 is  122      0...00001111010
         Flipped  1...11110000101
         +1       1...11110000110 = x

222 is            0...00011011110 = y

x & y             0...00010000110

正如您所演示的那样,Python显示的是什么。

注意,-122一直领先1到最高位。

答案 1 :(得分:1)

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

import math

def bin_format(integer):
    num_bytes = math.ceil(integer.bit_length()/8) # number req 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)