@woosh/meep-engine
Version:
Pure JavaScript game engine. Fully featured and production ready.
18 lines (15 loc) • 698 B
JavaScript
/**
* Count number of set bits (1s) in a 32bit integer
* @param {number} v
* @returns {number}
*/
export function bitCount(v) {
// see https://stackoverflow.com/a/109025/3973586
// see https://graphics.stanford.edu/%7Eseander/bithacks.html#CountBitsSetParallel
let i = v|0;
i = i - ((i >> 1) & 0x55555555); // add pairs of bits
i = (i & 0x33333333) + ((i >> 2) & 0x33333333); // quads
i = (i + (i >> 4)) & 0x0F0F0F0F; // groups of 8
i *= 0x01010101; // horizontal sum of bytes
return i >> 24; // return just that top byte (after truncating to 32-bit even when int is wider than uint32_t)
}