Skip to content

Instantly share code, notes, and snippets.

@imaami
Created April 16, 2024 20:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save imaami/11f1dd24400bf1ec95969a530994fb98 to your computer and use it in GitHub Desktop.
Save imaami/11f1dd24400bf1ec95969a530994fb98 to your computer and use it in GitHub Desktop.
Generic popcnt
#include <limits.h>
#include <stddef.h>
#include <stdint.h>
#define popcnt(x) (size_t)({\
typeof (_Generic(x, \
int32_t: (uint32_t)1, \
int64_t: (uint64_t)1, \
uint32_t: (uint32_t)1, \
uint64_t: (uint64_t)1))y=x; \
y-=y>>1U& (typeof(y))-1/ 3; \
y=(y>>2U& (typeof(y))-1/ 5) \
+ (y & (typeof(y))-1/ 5);\
(y+(y>>4)& (typeof(y))-1/17) \
* ( (typeof(y))-1/255)\
>>CHAR_BIT*(sizeof(y) -1); })
size_t popcnt32(uint32_t x){return popcnt(x);}
size_t popcnt64(uint64_t x){return popcnt(x);}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment