File tree Expand file tree Collapse file tree 1 file changed +40
-0
lines changed
Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Original file line number Diff line number Diff line change 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 }
You can’t perform that action at this time.
0 commit comments