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 ⌊log⁡2(n)⌋+1\lfloor \log_2(n) \rfloor + 1. For example, n=8=10002n = 8 = 1000_2 needs 44 bits, and log⁡2(8)=3\log_2(8) = 3.

Why? Because 2k−1≤n<2k2^{k-1} \leq n < 2^k, so k−1≤log⁡2(n)<kk - 1 \leq \log_2(n) < k, giving k=⌊log⁡2(n)⌋+1k = \lfloor \log_2(n) \rfloor + 1. This is why 3232-bit integers can hold values up to 232−12^{32} - 1.

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