Skip to content

Instantly share code, notes, and snippets.

@kspalaiologos
Created February 20, 2020 17:44
Show Gist options
  • Save kspalaiologos/3469e7c1835f414f721bbe206b3a5f88 to your computer and use it in GitHub Desktop.
Save kspalaiologos/3469e7c1835f414f721bbe206b3a5f88 to your computer and use it in GitHub Desktop.
Count set bits in O(1)
#include <inttypes.h>
uint16_t bits(int64_t a) {
uint64_t x;
a -= (a >> 1) & 0x5555555555555555;
x = ((a >> 2) & 0x3333333333333333) + (a & 0x3333333333333333);
return (((int64_t) ((x + (x >> 4)) & 0xf0f0f0f0f0f0f0f)) * ((int64_t) 0x101010101010101)) >> 56;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment