Skip to content

Instantly share code, notes, and snippets.

@heeh
Last active June 5, 2021 15:24
Show Gist options
  • Save heeh/e7d95047687775e37cf30ac9b9ddd55d to your computer and use it in GitHub Desktop.
Save heeh/e7d95047687775e37cf30ac9b9ddd55d to your computer and use it in GitHub Desktop.
Hamming Weight
fn countOnes(x: usize) -> usize {
let mut c = 0;
let mut x = x;
c = (x & 0x55555555) + ((x >> 1) & 0x55555555);
c = (c & 0x33333333) + ((c >> 2) & 0x33333333);
c = (c & 0x0f0f0f0f) + ((c >> 4) & 0x0f0f0f0f);
c = (c & 0x00ff00ff) + ((c >> 8) & 0x00ff00ff);
c = (c & 0x0000ffff) + ((c >> 16) & 0x0000ffff);
return c;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment