Created
February 20, 2020 17:44
-
-
Save kspalaiologos/3469e7c1835f414f721bbe206b3a5f88 to your computer and use it in GitHub Desktop.
Count set bits in O(1)
This file contains 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
#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