Math Fundamentals18 sections · 814 units
Open in Course

Logarithms and Bit Manipulation (Powers of 2)

Binary representation

The number of bits needed to represent nn in binary is log2(n)+1\lfloor \log_2(n) \rfloor + 1. For example, n=8=10002n = 8 = 1000_2 needs 44 bits, and log2(8)=3\log_2(8) = 3.

Why? Because 2k1n<2k2^{k-1} \leq n < 2^k, so k1log2(n)<kk - 1 \leq \log_2(n) < k, giving k=log2(n)+1k = \lfloor \log_2(n) \rfloor + 1. This is why 3232-bit integers can hold values up to 23212^{32} - 1.

Bit manipulation algorithms often run in O(logn)O(\log n) time because they process one bit per step, and there are O(logn)O(\log n) bits.