Skip to content

Commit a35ce8d

Browse files
authored
Create HammingWeight.js
Changes in name of algorithm.
1 parent 5fa4d6e commit a35ce8d

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

Bit-Manipulation/HammingWeight.js

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/**
2+
* github author: chrdek
3+
* license: GPL-3.0 or later
4+
*
5+
* @param {number} b = integer or, binary representation of it
6+
*
7+
* The following code generates the "hamming weight" for a binary sequence
8+
* of 32-bit integer values, producing the relevant integer code for it.
9+
*
10+
* Returns the overall of bit count population for values up to 65535, inclusive.
11+
*
12+
* This algorithm utilizes minimum amount of byte space reads and can be very easily
13+
* extended to its 64-bit counterpart.
14+
*
15+
**/
16+
17+
function HammingWeight(b) {
18+
//preallocate total number of bytes to count the bits population from
19+
let bytes = new Array(65536);
20+
21+
//count the bit allocation of the binary sequence by shift in place of the resulting bits
22+
//can be used with xor as well.
23+
const bitAlloc = (bin) => {
24+
let counter = 0;
25+
while (bin > 0) {
26+
counter += bin & 1;
27+
bin >>=1;
28+
}
29+
return counter;
30+
}
31+
32+
//count all 1-bits from entire bit set
33+
for (let k=0; k < 65536; k++)
34+
bytes[k] = bitAlloc(k);
35+
36+
//perform bit shifting for integer values for bit-populated result
37+
return bytes[b & 0xFFFF] + bytes[b >> 16];
38+
}
39+
40+
export { HammingWeight }

0 commit comments

Comments
 (0)