I found this strange if
-statement in somebody else’s code:
if variable & 1 == 0:
I don\'t understand it. It should have two
The & is a bitwise operator. It returns an integer with 1 bit for every bit of its two operands that are both 1, and 0 in all other places. For example:
a = 10 # 0b1010
b = 6 # 0b0110
a & b # 0b0010
Now, if you have variable & 1
, you're comparing variable
against 0b1
which will only return 1 if that last digit in the binary representation is a 1, otherwise a 0.