0

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

Please also help me 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
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
meallhour
  • 13,921
  • 21
  • 60
  • 117
  • `num&1` is the bitwise `and` of `num` and `1`. That is it tells you the value of the least significant bit in `num`. – quamrana Feb 25 '22 at 23:11
  • 4
    In the code given, it checks if the lowest bit of num is set. If it is, the value is evaluated as true. In other words, it's checking if the number is even or odd. – Nick ODell Feb 25 '22 at 23:12

1 Answers1

1

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)

rikyeah
  • 1,896
  • 4
  • 11
  • 21