问题
I've been learning about adding two numbers using bit manipulation and I am having issues understanding how it is done in Python for negative numbers. For example, if I am trying to &
the following:
-0b1111010 (-122) & 0b11011110 (222)
shouldn't it be:
0b1111010
& 0b11011110
------------
0b01011010
since only a combination of 1's results in 1's?
Right now python gives 0b10000110
I couldn't find any resources specifically when a negative number is added to a positive number using python.
回答1:
It's because Python uses a Two's complement binary signed integer representation. Here a snippet of code that shows the actual byte data and illustrates why you're getting the results that you are:
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))
Output:
10000110 (-122)
& 11011110 ( 222)
=================
10000110 ( 134)
回答2:
-122 is 122 0...00001111010
Flipped 1...11110000101
+1 1...11110000110 = x
222 is 0...00011011110 = y
x & y 0...00010000110
Which is what Python shows, as you demonstrated.
Note, that -122 has leading 1s all the way to the most significant bit.
来源:https://stackoverflow.com/questions/46044936/bitwise-and-between-negative-and-positive-numbers