Math Fundamentals18 sections · 814 units
Open in Course

Exponents and Bit Manipulation

Powers of 2 everywhere

Every power of 22 maps to a single bit. 20=12^0 = 1 is bit 00. 23=82^3 = 8 is bit 33. In code, 2k2^k is just 1 << k (left shift by kk).

This connection is everywhere. Checking if bit kk is set in a number nn: n & (1 << k). Setting bit kk: n | (1 << k). Clearing bit kk: n & ~(1 << k).

A number with all kk lower bits set is 2k12^k - 1. In binary, 241=15=111122^4 - 1 = 15 = 1111_2. You get this with (1 << k) - 1, and it's useful as a bitmask.

Checking if nn is a power of 22: n & (n - 1) == 0. A power of 22 has exactly one bit set. Subtracting 11 flips that bit and sets all lower bits, so the AND gives zero.