From b80479ec273dfa3a209e120dc61d9bc9c4f57612 Mon Sep 17 00:00:00 2001 From: David Garcia Quintas Date: Wed, 15 Jul 2015 17:46:05 -0700 Subject: [PATCH] Added population count function --- include/grpc/support/useful.h | 9 +++++++++ test/core/support/useful_test.c | 3 +++ 2 files changed, 12 insertions(+) diff --git a/include/grpc/support/useful.h b/include/grpc/support/useful.h index d3d8ad6437f..bbd9ea36ae2 100644 --- a/include/grpc/support/useful.h +++ b/include/grpc/support/useful.h @@ -34,6 +34,8 @@ #ifndef GRPC_SUPPORT_USEFUL_H #define GRPC_SUPPORT_USEFUL_H +#include + /* useful macros that don't belong anywhere else */ #define GPR_MIN(a, b) ((a) < (b) ? (a) : (b)) @@ -61,4 +63,11 @@ /** Get the \a n-th bit of \a i */ #define GPR_BITGET(i, n) (((i) & (1u << n)) != 0) +/** Returns number of bits set in bitset \a i */ +int gpr_bitcount(gpr_uint32 i) { + i = i - ((i >> 1) & 0x55555555); + i = (i & 0x33333333) + ((i >> 2) & 0x33333333); + return (((i + (i >> 4)) & 0xF0F0F0F) * 0x1010101) >> 24; +} + #endif /* GRPC_SUPPORT_USEFUL_H */ diff --git a/test/core/support/useful_test.c b/test/core/support/useful_test.c index 5827f0a6276..7129dce632d 100644 --- a/test/core/support/useful_test.c +++ b/test/core/support/useful_test.c @@ -57,9 +57,12 @@ int main(int argc, char **argv) { GPR_ASSERT(GPR_ARRAY_SIZE(five) == 5); GPR_ASSERT(GPR_BITSET(&bitset, 3) == 8); + GPR_ASSERT(gpr_bitcount(bitset) == 1); GPR_ASSERT(GPR_BITGET(bitset, 3) == 1); GPR_ASSERT(GPR_BITSET(&bitset, 1) == 10); + GPR_ASSERT(gpr_bitcount(bitset) == 2); GPR_ASSERT(GPR_BITCLEAR(&bitset, 3) == 2); + GPR_ASSERT(gpr_bitcount(bitset) == 1); GPR_ASSERT(GPR_BITGET(bitset, 3) == 0); return 0;