Math Fundamentals18 sections · 814 units
Open in Course

Checking if a Bit is Set

Test individual bits

To check if bit kk is set (equals 1) in number nn, you AND nn with 2k2^k. If the result is non-zero, the bit is set.

Why does this work? The number 2k2^k has only one bit set: bit kk. When you AND with nn, all other bits become 0. Only bit kk survives if it was 1 in nn.

Example: Check if bit 2 is set in 13=110113 = 1101. Compute 13&(1<<2)=13&4=1101&0100=0100=413 \& (1 << 2) = 13 \& 4 = 1101 \& 0100 = 0100 = 4. Non-zero, so bit 2 is set.