简体   繁体   中英

Bitwise AND (&) between negative and positive numbers?

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.

-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.

It's because Python uses a two's complement binary signed integer representation. Here a snippet of code whose output 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 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))

Output:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM