Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficiently count the number of bits in an integer in JavaScript

Tags:

Let's say I have an integer I and want to get the count of 1s in its binary form.

I am currently using the following code.

Number(i.toString(2).split("").sort().join("")).toString().length; 

Is there a faster way to do this? I am thinking about using bitwise operators. Any thoughts?

NOTE: i is within the 32-bit limitation.

like image 953
Ming Huang Avatar asked Mar 30 '17 15:03

Ming Huang


People also ask

How do you find the number of set bits in an integer?

We can also use bitset::count(), an inbuilt STL in C++ that returns the count of the total number of set bits in an integer.

How many bits is a JavaScript integer?

The JavaScript Number type is a double-precision 64-bit binary format IEEE 754 value, like double in Java or C#.

How many bits are in an integer?

Integer, 32 Bit data type is the default for most numerical tags where variables have the potential for negative or positive values.


1 Answers

You can use a strategy from this collection of Bit Twiddling Hacks:

function bitCount (n) {    n = n - ((n >> 1) & 0x55555555)    n = (n & 0x33333333) + ((n >> 2) & 0x33333333)    return ((n + (n >> 4) & 0xF0F0F0F) * 0x1010101) >> 24  }    console.log(bitCount(0xFF)) //=> 8

Note that the above strategy only works for 32-bit integers (a limitation of bitwise operators in JavaScript).

A more general approach for larger integers would involve counting 32-bit chunks individually (thanks to harold for the inspiration):

function bitCount (n) {    var bits = 0    while (n !== 0) {      bits += bitCount32(n | 0)      n /= 0x100000000    }    return bits  }    function bitCount32 (n) {    n = n - ((n >> 1) & 0x55555555)    n = (n & 0x33333333) + ((n >> 2) & 0x33333333)    return ((n + (n >> 4) & 0xF0F0F0F) * 0x1010101) >> 24  }    console.log(bitCount(Math.pow(2, 53) - 1)) //=> 53

You could also use a regular expression:

function bitCount (n) {    return n.toString(2).match(/1/g).length  }    console.log(bitCount(0xFF)) //=> 8
like image 195
gyre Avatar answered Sep 17 '22 13:09

gyre