Skip to content

Instantly share code, notes, and snippets.

@di3
Created Apr 10, 2019
Embed
What would you like to do?
//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