Emmanuel Akinfulubi

JavaScriptMath

Count set bits in a number in JavaScript

Advanced · 4 min read

How many 1s are in the binary form of a number? 7 is 111, so it has three. 256 is 100000000, so it has one. This count is called the population count, or popcount, and the 1 bits are called set bits.

It sounds like a puzzle, but it is used for real work. If each bit stands for a permission or a feature, the popcount tells you how many are switched on. Comparing two bit patterns and counting where they differ (the Hamming distance) is used to catch errors in transmitted data and to compare image fingerprints. In this tutorial you will count set bits two ways, then find the numbers where each way gives the wrong answer. You need to know the bitwise operators & and ^.

The trick: x & (x - 1)

Subtracting 1 from a number has a neat effect in binary. The lowest 1 bit turns into 0, and every 0 below it turns into 1. Everything above stays the same:

Output

x       = 1011000
x - 1   = 1010111
x & (x - 1) = 1010000

ANDing the two keeps only the bits they share, so the result is x with its lowest 1 bit removed. Do that again and again until nothing is left, and the number of times you did it is the number of 1 bits. This loop is known as Kernighan's method.

A loop that stops at 0

In JavaScript, while (x) keeps going while x is truthy. Every number except 0 (and NaN) is truthy, so the loop stops exactly when x reaches 0.

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

70 Counting the set bits

hard

Count the 1 bits in a number with Kernighan's loop, x &= x - 1. Then run it on -1 and on 2 ** 53 - 1, compare it with counting characters in toString(2), and find where each one lies.

Stuck? Three hints, smallest first
  1. 1. x & (x - 1) clears the lowest set bit, so the loop runs once per bit set.
  2. 2. For a negative, toString(2) gives a minus sign and the magnitude, so counting characters answers a different question.
  3. 3. The loop is bitwise, so it only ever sees 32 bits. BigInt does not have that limit.

Step 1: the popcount loop

Step 1

function popcount(n) {
  let x = n;
  let count = 0;
  while (x) {                          // each pass clears one bit, so at most 32 passes
    x &= x - 1;
    count++;
  }
  return count;
}
console.log([0, 1, 7, 255, 256, 1023].map(popcount)); // [ 0, 1, 3, 8, 1, 10 ]

x &= x - 1 is short for x = x & (x - 1). The loop runs once per set bit, so 255 (11111111) takes 8 passes and 256 takes just 1.

Step 2: a negative number

Step 2

console.log(popcount(-1)); // 32

Bitwise operators work on 32-bit signed whole numbers, and -1 is stored as thirty-two 1 bits. The loop clears them one at a time and stops after 32 passes. A negative number doesn't make it loop forever.

Step 3: counting characters instead

A second idea: write the number in binary with toString(2) and count the '1' characters.

Step 3

const byString = (n) => [...n.toString(2)].filter((c) => c === '1').length;
console.log(byString(255)); // 8
console.log((-1).toString(2), byString(-1)); // -1 1

[...text] splits a string into its characters. For 255 this agrees with the loop. For -1 it says 1, because toString(2) writes a minus sign and then the digits of 1. It never shows the 32-bit pattern.

To count the stored bits, first read the number as unsigned with >>> 0:

Step 3 fixed

const unsigned = (n) => byString(n >>> 0);
console.log(unsigned(-1)); // 32

Step 4: a number bigger than 32 bits

2 ** 53 - 1 is the largest whole number JavaScript stores exactly, and in binary it is fifty-three 1s.

Step 4

const wide = 2 ** 53 - 1;              // 53 bits set, all of them
console.log(byString(wide)); // 53
console.log(popcount(wide)); // 32

Now the string method is right and the loop is wrong. The bitwise operators only ever see the bottom 32 bits, so the loop never notices the other 21. Here is a 33-bit example:

JavaScript

console.log(popcount(2 ** 32 + 1), byString(2 ** 32 + 1)); // 1 2

2 ** 32 + 1 is a 1, thirty-one 0s, and another 1. The loop only sees the bottom 32 bits, which hold just the last 1.

So each method fails somewhere: the loop above 32 bits, the string method on negatives.

Step 5: BigInt has no 32-bit limit

BigInt is JavaScript's type for whole numbers of any size. Its bitwise operators work on every bit, however many there are. The same loop works if you use BigInt values, written with an n on the end:

Step 5

function bigPopcount(n) {
  let x = BigInt(n);
  let count = 0;
  while (x) {
    x &= x - 1n;
    count++;
  }
  return count;
}
console.log(bigPopcount(wide)); // 53

x - 1n because you can't mix BigInt and ordinary numbers in one sum. 0n is falsy, just like 0, so the loop stops in the same way.

Step 6: Hamming distance

XOR gives 1 wherever two patterns differ. Count those 1s and you have the number of positions that differ:

Step 6

const hamming = (a, b) => popcount(a ^ b);
console.log(hamming(0b1011, 0b1101)); // 2

1011 and 1101 differ in the middle two positions, so the distance is 2.

The full solution

The answer panel has popcount, byString, unsigned, bigPopcount and hamming, and prints the small counts, -1 counted every way, 2 ** 53 - 1 by loop, by string and as a BigInt, and the Hamming distance. Press Run to see the output.

The answer

function popcount(n) {
  let x = n;
  let count = 0;
  while (x) {                          // each pass clears one bit, so at most 32 passes
    x &= x - 1;
    count++;
  }
  return count;
}

const byString = (n) => [...n.toString(2)].filter((c) => c === '1').length;
const unsigned = (n) => byString(n >>> 0);

function bigPopcount(n) {
  let x = BigInt(n);
  let count = 0;
  while (x) {
    x &= x - 1n;
    count++;
  }
  return count;
}

const hamming = (a, b) => popcount(a ^ b);
const wide = 2 ** 53 - 1;              // 53 bits set, all of them

console.log('0, 1, 7, 255, 256, 1023:', [0, 1, 7, 255, 256, 1023].map(popcount));
console.log('-1                     :', popcount(-1), 'bits set');
console.log('by string, -1          :', byString(-1), '<- counting the wrong thing');
console.log('after >>> 0            :', unsigned(-1));
console.log('2 ** 53 - 1            :', popcount(wide), 'by loop,', byString(wide), 'by string');
console.log('as BigInt              :', bigPopcount(wide));
console.log('hamming(1011, 1101)    :', hamming(0b1011, 0b1101));

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 low numbers, counted', [0, 1, 7, 255, 256, 1023].map(popcount), [0, 1, 3, 8, 1, 10]);
test('-1 has all 32 bits set, and the loop still terminates', popcount(-1), 32);
test('counting characters in toString(2) says 1, because of the minus sign', [(-1).toString(2), byString(-1)], ['-1', 1]);
test('coercing with >>> 0 first fixes it', unsigned(-1), 32);
test('2 ** 53 - 1 really has 53 bits set, and the string method finds them', byString(wide), 53);
test('but the bitwise loop only ever sees 32 of them', popcount(wide), 32);
test('BigInt has no 32-bit limit, so the same loop is right there', bigPopcount(wide), 53);
test('and a 33-bit value is miscounted too: 2 ** 32 + 1 has two bits', [popcount(2 ** 32 + 1), byString(2 ** 32 + 1)], [1, 2]);
test('popcount of a XOR is the Hamming distance between two patterns', hamming(0b1011, 0b1101), 2);

x &= x - 1 clears the lowest set bit — subtracting 1 flips that bit to 0 and every bit below it to 1, and the AND keeps only what both have. So the loop runs exactly as many times as there are bits set, which for a 32-bit value is at most 32. That bound is also why it terminates for a negative: -1 is thirty-two 1s, and it takes thirty-two passes to walk them off.

Both methods are wrong somewhere, in opposite directions. The bitwise loop is blind past bit 31, so 2 ** 53 - 1 reports 32 instead of 53 and 2 ** 32 + 1 reports 1 instead of 2. The string method sees the whole number but is reading a rendered decimal-to-binary conversion, so a negative gives it a minus sign and it counts 1 for -1; n >>> 0 first, and it agrees. Above 32 bits, use BigInt: its bitwise operators are arbitrary width, so the identical loop is correct.

Common mistakes

  • Counting characters of a negative number. (-1).toString(2) is '-1', so you count 1 instead of 32. Use n >>> 0 first.
  • Using the bitwise loop past 32 bits. It quietly ignores every bit above bit 31. Use BigInt for big numbers.
  • Mixing BigInt and numbers. x - 1 when x is a BigInt throws a TypeError. Write x - 1n.

Try it yourself

  1. Use popcount to find every number from 0 to 64 that has exactly one set bit. What do they have in common?
  2. Write isPowerOfTwo(n) using n > 0 && (n & (n - 1)) === 0, and explain it with what you learned in this lesson.
  3. Find the Hamming distance between 255 and 0, and between 170 (10101010) and 85 (01010101).

Keep practising

Newsletter

New writing, when it lands.

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