Predict the output
What does this print?
x = 0b10110
print(x & -x, x & (x - 1), x | 1, x ^ (1 << 4), bin(x >> 2))Choose an answer, then open Show answer below to check it.
Show answer
Answer: A 2 20 23 6 0b101
Right: lowest bit 2, clearing it gives 20, setting bit 0 gives 23, flipping bit 4 gives 6, and shifting gives 101.
Each of these is one machine operation, which is why bit tricks replace loops in tight code.
Why not the others?
- B 2 21 23 6 0b101. x & (x - 1) clears bit 1: 10110 becomes 10100, which is 20.
- C 1 20 23 38 0b101. The lowest 1 bit of 10110 is worth 2, and flipping bit 4 turns it off.