Search code examples
pythonbit-manipulationbitwise-operatorsbit-shift

& Bit operation in python


In doing a bitwise &, I thought by specifying the digit it would add that digit in the necessary spot, but in python I get the following:

>>> 4&2
0

>>> 4&1<<1
0

>>> 0b100 & 0b010
0

I thought that this would give 110 or 6, but it seems like either I'm misunderstanding the & operator. What am I doing wrong here or misunderstanding in the above?


Solution

  • Bitwise & gives you a 1 in a bit position only if all operands have a 1 in that position. You are looking for bitwise |.