2017-09-04 169 views
0

我一直在学习如何使用位操作来添加两个数字,并且我在理解在Python中如何完成负数的问题。例如,如果我想&如下:负数与正数之间的按位与(&)?

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

它不应该是:

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

,因为只有在1的1的结果相结合?

眼下蟒蛇给0b10000110

我不能具体找到任何资源时负数,则使用Python加入到正数。

+2

-0b1111010是0b ... 10000110。 –

+1

Python中的负整数表示[2的补码](https://en.wikipedia.org/wiki/Two%27s_complement)表示;负整数的按位运算相应地起作用。 –

+0

你想要做什么?通常,按位&用于逻辑操作,而不是算术。 -122&222不会“添加”这些值。它对每对比特执行逻辑“和”操作。要添加值,您可以使用'+'。 –

回答

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) 
0
-122 is 122  0...00001111010 
     Flipped 1...11110000101 
     +1  1...11110000110 = x 

222 is   0...00011011110 = y 

x & y    0...00010000110 

这是什么Python的节目,就像你演示的那样。

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