1

This looks like it works well on integers that are within the max integer size in JavaScript:

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
}

I'm wondering though how to count bits generally, on any sized bit stream, efficiently, ideally without converting to string.

3
  • There are no bit streams in JavaScript. The closest is probably ArrayBuffer, is that what you mean? Get a 32-bit view on it and run your function. Commented Mar 10, 2019 at 23:30
  • Yes, basically just a long ArrayBuffer of arbitrary size. Commented Mar 10, 2019 at 23:30
  • I would just loop over it as bytes (perhaps shorts), and sum bitcounts from a pre-computed array. Commented Mar 10, 2019 at 23:33

2 Answers 2

1

The comment with the lookup table, roughly:

var lookup=new Uint8Array(256);
for(var i=0;i<256;i++){
  var c=0;
  for(var j=i;j;j>>=1)
    if(j&1)c++;
  lookup[i]=c;
}
function count(arr){
  var arr8=new Uint8Array(arr);
  return arr8.reduce((a,e)=>a+lookup[e],0);
}

console.log(count(new Uint8Array([0x12,0x34,0x56,0x78,0x9A,0xBC,0xDE,0xF])));
                                  //11   21   22   31   22   32   33   4 = 32

Of course the table-generation could use your magic too.

Sign up to request clarification or add additional context in comments.

Comments

1

If you know your buffer will have length divisible by 4,

let array32 = new Uint32Array(buffer);
let numBits = array32.reduce((a, e) => a + bitCount32(e), 0);

Otherwise probably tevemadar's suggestion is better, use Uint8Array and count bits in a byte, not in a dword.

3 Comments

Ehehe, I believed you in the middle of the night. But reduce: initialValue [...] If no initial value is supplied, the first element in the array will be used.
Eh happens when you don’t test... How about now?
I guess it should work, at least mine does, and this was the only problem with it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.