Math Fundamentals18 sections · 814 units
Open in Course

Setting a Bit

Turn a bit on

To set bit kk (make it 1) in number nn, you OR nn with 2k2^k. This guarantees bit kk becomes 1, while leaving all other bits unchanged.

The OR operation turns bits on. Since 11=11 | 1 = 1 and 01=10 | 1 = 1, ORing with a bit that's 1 forces that position to 1 regardless of what was there before.

Example: Set bit 1 in 12=110012 = 1100. Compute 12(1<<1)=122=11000010=1110=1412 | (1 << 1) = 12 | 2 = 1100 | 0010 = 1110 = 14. Bit 1 is now on.