Search code examples
javascriptbinarybit

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

  • 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.