pythonbit-manipulationbitwise-operatorscollatz

When to use the bitwise and operator (&)?


I understand that the bitwise and operator (&) is equivalent to a product of two bit values. When would I use it?

I am also keen to understand what num&1 does in the code below:

def func(num):
    n = 1 + func((3*num+1) if num&1 else (num>>1))
    return n

Solution

  • As the comments mentioned, num&1 is a bitwise AND between num and 1.

    Since 1 in binary is ...000000001, the AND will result True iff the least significant bit of num is 1, in other words, if it is odd (here some explanation of binary)