Added population count function

pull/2463/head
David Garcia Quintas 10 years ago
parent ed7e8550f5
commit b80479ec27
  1. 9
      include/grpc/support/useful.h
  2. 3
      test/core/support/useful_test.c

@ -34,6 +34,8 @@
#ifndef GRPC_SUPPORT_USEFUL_H #ifndef GRPC_SUPPORT_USEFUL_H
#define GRPC_SUPPORT_USEFUL_H #define GRPC_SUPPORT_USEFUL_H
#include <grpc/support/port_platform.h>
/* useful macros that don't belong anywhere else */ /* useful macros that don't belong anywhere else */
#define GPR_MIN(a, b) ((a) < (b) ? (a) : (b)) #define GPR_MIN(a, b) ((a) < (b) ? (a) : (b))
@ -61,4 +63,11 @@
/** Get the \a n-th bit of \a i */ /** Get the \a n-th bit of \a i */
#define GPR_BITGET(i, n) (((i) & (1u << n)) != 0) #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 */ #endif /* GRPC_SUPPORT_USEFUL_H */

@ -57,9 +57,12 @@ int main(int argc, char **argv) {
GPR_ASSERT(GPR_ARRAY_SIZE(five) == 5); GPR_ASSERT(GPR_ARRAY_SIZE(five) == 5);
GPR_ASSERT(GPR_BITSET(&bitset, 3) == 8); GPR_ASSERT(GPR_BITSET(&bitset, 3) == 8);
GPR_ASSERT(gpr_bitcount(bitset) == 1);
GPR_ASSERT(GPR_BITGET(bitset, 3) == 1); GPR_ASSERT(GPR_BITGET(bitset, 3) == 1);
GPR_ASSERT(GPR_BITSET(&bitset, 1) == 10); GPR_ASSERT(GPR_BITSET(&bitset, 1) == 10);
GPR_ASSERT(gpr_bitcount(bitset) == 2);
GPR_ASSERT(GPR_BITCLEAR(&bitset, 3) == 2); GPR_ASSERT(GPR_BITCLEAR(&bitset, 3) == 2);
GPR_ASSERT(gpr_bitcount(bitset) == 1);
GPR_ASSERT(GPR_BITGET(bitset, 3) == 0); GPR_ASSERT(GPR_BITGET(bitset, 3) == 0);
return 0; return 0;

Loading…
Cancel
Save