'How to count 1 bits in an integer in JavaScript

How to count the number of 1 bits in an integer.

So say you have the binary number 11100000. Basically there are 3 boolean flags at the beginning. The corresponding decimal notation for this is 224. Wondering how to take that integer and loop through it somehow to add the number of 1s that it starts with. Something like this:

var int = 224
var n = 8
var i = 0
var total = 0
while (i++ < n) {
  if (int.getBitAt(i) == 1) {
    total++
  } else {
    break
  }
}

I've never really dealt with bits so not sure how to accomplish this in an optimal way (i.e. without converting it to a string '11100000' or other unoptimal ways.



Solution 1:[1]

So here's another arbitrary bit length solution using bit twiddling:

function countBits(num){
    var idx=Math.floor(Math.log2(num)); //Get the number of bits needed to represent your number
    var bit=1;
    var count=0;
    while (bit){
        bit=(num & (1<<idx))>>idx; //Check the bit value in the given position
        count+=bit; //Add it to the count
        idx-=1; //Check the next bit over
    }
    return count;
}

Solution 2:[2]

const num = 42726; // value to count set bits in
const numBytes = 2; // number of bytes used to represent num
let i = 0;
let count = 0;
while (i < numBytes * 8) {
  if (((1 << i) & num) >> i === 1) count++;
  i++;
}
console.log(count); // 9

Solution 3:[3]

A way to do it for arbitrary bit length numbers could be something like:

function countBits(num){
    var s=num.toString(2); //Converts the number to a binary string
    if (s[0]==='0'){return 0;} //If the first digit is 0, return 0
    return s.split('0')[0].length; //Otherwise, return the number of 1s at the start
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 sbrass
Solution 2 Famous Ketoma
Solution 3 sbrass