Math Fundamentals18 sections · 814 units
Open in Course

Toggling a Bit

Flip a bit

To toggle bit kk (flip 0 to 1 or 1 to 0) in number nn, you XOR nn with 2k2^k. In code: n(1<<k)n \wedge (1 << k).

XOR flips bits because 01=10 \wedge 1 = 1 and 11=01 \wedge 1 = 0. When you XOR with a 1, that bit flips. When you XOR with a 0, the bit stays the same.

Example: Toggle bit 1 in 12=110012 = 1100. Compute 122=11000010=1110=1412 \wedge 2 = 1100 \wedge 0010 = 1110 = 14. Bit 1 flipped from 0 to 1. Toggle again: 142=1100=1214 \wedge 2 = 1100 = 12. It's back.