@woosh/meep-engine
Version:
Pure JavaScript game engine. Fully featured and production ready.
23 lines (18 loc) • 822 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
// Force to a 32-bit unsigned integer
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
// horizontal sum of bytes
// return just that top byte (after truncating to 32-bit even when int is wider than uint32_t)
// Math.imul perfectly simulates C's 32-bit integer multiplication overflow
return (Math.imul(i, 0x01010101) >>> 24);
}