2017-09-04 23 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到最高有效位。