Emmanuel Akinfulubi

JavaScriptMath

Check if a number is a power of two in JavaScript

Intermediate · 4 min read

A power of two is a number you get by multiplying 2 by itself some number of times: 1, 2, 4, 8, 16, 1024 and so on. Powers of two are everywhere in computing. Memory sizes, texture sizes in games, and buffer sizes are often required to be one.

There is a famous one-line test for them, n & (n - 1), that shows up in interviews and in code all over the internet. In this tutorial you will write it, then find a number where it confidently gives the wrong answer in JavaScript. You will fix it with Math.log2, find where that fix goes wrong too, and end with a slow but correct version. You need to know what binary numbers are, at least roughly.

Powers of two in binary

In binary, every power of two is a 1 followed by zeros. 8 is 1000. 1024 is a 1 followed by ten zeros. Subtract 1 and every bit flips below that 1: 8 - 1 is 7, which is 111.

JavaScript

console.log((8).toString(2)); // 1000
console.log((7).toString(2)); // 111

The & operator

& is bitwise AND. It lines up two numbers in binary and keeps a 1 only where both have a 1. For 8 and 7 there is no position where both have a 1, so the result is 0. For 12 (1100) and 11 (1011) they share the top bit, so the result is 8 (1000).

JavaScript

console.log(8 & 7);   // 0
console.log(12 & 11); // 8

So n & (n - 1) is 0 exactly when n has a single 1 bit, which means n is a power of two.

Here is the exercise. Try it yourself first if you like, then read on and we will build it together.

48 Powers of two, and the limits of the bitwise trick

fair

Test whether a number is a power of two with n & (n - 1). Then find a number where that trick reports true and is wrong, fix it with Math.log2, and find a number where the fix is wrong too.

Stuck? Three hints, smallest first
  1. 1. A power of two has exactly one bit set, so subtracting 1 flips every bit below it and the AND is 0.
  2. 2. Every bitwise operator in JavaScript converts its operands to a signed 32-bit integer first.
  3. 3. Math.log2 returns a double, so a whole-looking result does not prove the input was a power of two.

Step 1: the bitwise test

Step 1

const byBits = (n) => n > 0 && (n & (n - 1)) === 0;
console.log([1, 2, 3, 4, 1023, 1024].map(byBits)); // [ true, true, false, true, false, true ]

The brackets around n & (n - 1) matter: in JavaScript === is checked before &, so without them you would be comparing (n - 1) === 0 first. The n > 0 part rules out 0, which would otherwise pass, since 0 & -1 is 0.

Step 2: the number that breaks it

Try a number just above 2 to the 32nd, 4294967297. It is odd, so it can't be a power of two.

Step 2

const beyond32 = 2 ** 32 + 1;
console.log(beyond32);          // 4294967297
console.log(byBits(beyond32));  // true

Wrong, and with no warning. The reason: every bitwise operator in JavaScript (&, |, ^, ~, <<, >>) first converts its numbers to 32-bit integers. Anything above that range is wrapped around. You can see it with | 0, which does that conversion and nothing else:

Step 2

console.log(beyond32 | 0);        // 1
console.log((3 * 2 ** 32) | 0);   // 0
console.log(1 << 32);             // 1

4294967297 arrives as 1, and 1 is a power of two. 3 * 2 ** 32 arrives as 0. Even 1 << 32 gives 1, because a shift count is wrapped to 32 bits too. The trick is fine. JavaScript's bitwise math is what makes it reliable only below 2 to the 31st.

Step 3: fix it with Math.log2

Math.log2(n) answers "2 to the power of what gives n?". For a power of two, the answer is a whole number.

Step 3

console.log(Math.log2(1024)); // 10
console.log(Math.log2(1000)); // 9.965784284662087

const byLog = (n) => n > 0 && Number.isInteger(n) && Number.isInteger(Math.log2(n));
console.log(byLog(beyond32));    // false
console.log(byLog(3 * 2 ** 32)); // false

No 32-bit conversion, so both large numbers are now handled correctly.

Step 4: where the fix breaks

Try a bigger odd number, 2 to the 49th plus 1:

Step 4

const odd49 = 2 ** 49 + 1;
console.log(odd49);              // 562949953421313
console.log(odd49 % 2);          // 1
console.log(Math.log2(odd49));   // 49
console.log(byLog(odd49));       // true

It is odd, so it can't be a power of two, yet byLog says it is. The true log2 of this number is 49 plus a tiny fraction, so tiny that a JavaScript number can't hold it, and it rounds to exactly 49. Any test built on a logarithm is only as precise as the logarithm.

Step 5: halving, slow and right

The plain definition still works: keep dividing by 2 while the number is even. If you end at 1, it was a power of two.

Step 5

function byHalving(n) {
  if (!Number.isInteger(n) || n < 1) return false;
  while (n % 2 === 0) n /= 2;
  return n === 1;
}
console.log([1, 1024, 2 ** 32, beyond32, 3 * 2 ** 32, odd49].map(byHalving));
// [ true, true, true, false, false, false ]

All six are right. Dividing an even number by 2 is always exact in JavaScript, so there is no rounding anywhere. The loop runs at most about 1000 times even for the largest numbers, which is fast enough for almost any use.

Step 6: two more bit tricks

n & (n - 1) clears the lowest 1 bit of n. A related trick, n & -n, keeps only the lowest 1 bit:

Step 6

console.log(12 & 11);  // 8
console.log(12 & -12); // 4

Both are handy inside the 32-bit range. If you need them on large numbers, BigInt has its own & that is not limited to 32 bits.

The full solution

The answer panel has byBits, byLog and byHalving, then prints the small values, the 32-bit failure and its cause, the log2 fix, the 2 to the 49th failure and the halving results. Press Run to see the output.

The answer

const byBits = (n) => n > 0 && (n & (n - 1)) === 0;
const byLog = (n) => n > 0 && Number.isInteger(n) && Number.isInteger(Math.log2(n));

// Slow, and right: divide out every factor of 2 and see what is left.
function byHalving(n) {
  if (!Number.isInteger(n) || n < 1) return false;
  while (n % 2 === 0) n /= 2;
  return n === 1;
}

const beyond32 = 2 ** 32 + 1;          // 4294967297, plainly not a power of two
const odd49 = 2 ** 49 + 1;             // 562949953421313, also plainly not

console.log('small values   :', [1, 2, 3, 4, 1023, 1024].map(byBits));
console.log('2**32 + 1      :', byBits(beyond32), '<- wrong');
console.log('coerced to int32:', beyond32 | 0, 'and 3 * 2**32 becomes', (3 * 2 ** 32) | 0);
console.log('by log2        :', byLog(beyond32), '<- fixed');
console.log('2**49 + 1      :', byLog(odd49), '<- wrong again, log2 says', Math.log2(odd49));
console.log('by halving     :', [beyond32, odd49].map(byHalving));

Output


      
9 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 9 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

9 checks

test('the bitwise test is right below 2 ** 31', [1, 2, 3, 4, 1023, 1024].map(byBits), [true, true, false, true, false, true]);
test('it reports true for 2 ** 32 + 1 and for 3 * 2 ** 32', [byBits(beyond32), byBits(3 * 2 ** 32)], [true, true]);
test('because bitwise operators truncate to 32 bits first', [beyond32 | 0, (3 * 2 ** 32) | 0], [1, 0]);
test('a shift count is taken modulo 32, so 1 << 32 is 1, not 4294967296', [1 << 32, 1 << 31], [1, -2147483648]);
test('Math.log2 fixes both of those', [byLog(beyond32), byLog(3 * 2 ** 32)], [false, false]);
test('but it reports true for 2 ** 49 + 1, an odd number', [byLog(odd49), odd49 % 2], [true, 1]);
test('because log2 of it rounds to exactly 49', Math.log2(odd49), 49);
test('halving is the only one of the three that gets all of them right', [1, 1024, 2 ** 32, beyond32, 3 * 2 ** 32, odd49].map(byHalving), [true, true, true, false, false, false]);
test('n & (n - 1) clears the lowest set bit, n & -n isolates it', [12 & 11, 12 & -12], [8, 4]);

The trick itself is sound: one bit set means n - 1 flips everything below it and the AND is zero. What breaks is JavaScript's arithmetic. &, |, ^, <<, >> and ~ all convert to a signed 32-bit integer first, so 2 ** 32 + 1 arrives as 1, 1 & 0 is 0, and the answer is confidently wrong. Same reason ~~ is not a general truncation and 1 << 32 is 1.

The log2 repair is more interesting for failing later rather than not at all. Math.log2(2 ** 49 + 1) is 49 to the last bit a double can hold, so an integrality test on it cannot distinguish 2 ** 49 from its neighbour. Any predicate built on a logarithm inherits the resolution of the logarithm. The halving loop is the slowest and the only one that answers the question that was asked; BigInt with & is the fast alternative, since BigInt bitwise operators are not truncated to 32 bits.

Common mistakes

  • Using n & (n - 1) on large numbers. Bitwise operators wrap numbers to 32 bits, so 4294967297 passes as if it were 1.
  • Leaving out the brackets. n & (n - 1) === 0 compares first and ANDs second. Write (n & (n - 1)) === 0.
  • Trusting Number.isInteger(Math.log2(n)). It works further up, but 2 to the 49th plus 1 still passes.

Try it yourself

  1. Write nextPowerOfTwo(n) that returns the smallest power of two that is at least n, using a loop that doubles.
  2. Rewrite byBits with BigInt (n & (n - 1n)) and check it against 4294967297n.
  3. Check that byLog(2 ** 48 + 1) is still false. Then work out why 2 to the 49th plus 1 is the first of these numbers that fools it.

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.