Created
April 10, 2019 03:46
-
-
Save di3/234e1ad62f454755d46a996f102f8d37 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Hamming weight | |
export const getBitCount32 = (n) => { | |
n = n - ((n >> 1) & 0x55555555); | |
n = (n & 0x33333333) + ((n >> 2) & 0x33333333); | |
return ((n + (n >> 4) & 0xF0F0F0F) * 0x1010101) >> 24; | |
} | |
export const getBitCount = (n) => { | |
let str = n.toString(2), count = 0; | |
for (let i = str.length - 1; i >= 0; i--) { | |
if (str[i] === "1") ++count; | |
} | |
return count; | |
} | |
//returns from left (0) to right(n) by position(0-n) | |
//step 1: binary left shift eg: x = 110100000 p = 1 -> 000000011 | |
//step 2: binary and 1: 000000011 & 000000001 -> 000000001 | |
export const getLeftPosition = (value, position) => { | |
return (((value >> (8 - position)) & 1) == 1); | |
} | |
//its same as: value + Math.pow(2, 8 - position); | |
export const addLeftPosition = (value, position) => { | |
return value | (1 << (8 - position)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment