LOGBOOK

HELP

Quiz Entry - updated: 2026.07.07

How do you quickly compute powers of 2 and check if a number is a power of 2?

A power of two has exactly one bit set: 1 << k gives 2^k, and n != 0 && (n & (n-1)) == 0 tests whether n is a power of two.

Computing powers of 2:

1 << 0  = 1      (2⁰)
1 << 1  = 2      (2¹)
1 << 10 = 1024   (2¹⁰)
1 << 20 = 1048576 (2²⁰, ~1 million)

Checking if n is a power of 2:

// Classic trick: powers of 2 have exactly one bit set
bool isPowerOf2(unsigned n) {
    return n != 0 && (n & (n - 1)) == 0;
}

Why n & (n-1) works:

n   = 01000000  (64, power of 2)
n-1 = 00111111  (63)
AND = 00000000  ✓ Power of 2!

n   = 01100000  (96, not power of 2)
n-1 = 01011111  (95)
AND = 01000000  ✗ Not zero, not power of 2

Useful power-of-2 facts:

  • 1 << 10 = 1,024 ≈ 1K (kilo)
  • 1 << 20 = 1,048,576 ≈ 1M (mega)
  • 1 << 30 = 1,073,741,824 ≈ 1G (giga)

Tip: n & (n-1) clears the lowest set bit. For powers of 2, that's the only bit!

Go deeper:

From Quiz: REVE1 / Number Representations | Updated: Jul 07, 2026