Lance Pollard
Lance Pollard

Reputation: 79268

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.

Upvotes: 2

Views: 3327

Answers (4)

Famous Ketoma
Famous Ketoma

Reputation: 21

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

Upvotes: 0

bracco23
bracco23

Reputation: 2211

The easiest way to get such a thing is using bitwise operators. Basically:

var num = 224
var n = 8
var i = 0
var total = 0
while (i++ < n) {
  var mask = 1 << i
  if ( (mask & num) == (mask)) {
    total++
  }
}

Basically mask is a variable which is 1 at one place and 0 at all other places, like 0001000 with the high bit at i position.

mask & int is all zero if the i bit of int is 0, equal to mask if it is 1.

EDIT: I gave some tries on the console. First of all I got rid of the break, then I added some parenthes in the if statement. Probably some problems with the representation for the numbers made impossible for the statement to be true.

Upvotes: 1

sbrass
sbrass

Reputation: 995

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;
}

Upvotes: 1

sbrass
sbrass

Reputation: 995

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
}

Upvotes: -1

Related Questions