Search code examples
pythonoperatorsbitwise-operators

Why does Python return 0 for this & operation?


I'm learning Python and messing around with operations when I tried

>>> 14 & 16
0
>>> 0b1110 & 0b10000
0

In my head it would look like this:

>>> 0b1110 & 0b10000
1

From my understanding the & operator compares the 2 numbers in bit form to see if each bit is 1 and if so assigns a 1 to the returned value.

So why would this return 0 instead of 1?


Solution

  • Bits are right-aligned (padding with 0 on the left as necessary), so 14 & 16 compares as

       1110
    & 10000
      -----
      00000
    

    not

       1110
    &  10000
       -----
       10000  (16, not 1)