From 56ab253307c128cd99342ab1b6809e02b3fe9dcc Mon Sep 17 00:00:00 2001 From: rubidium Date: Sat, 1 Sep 2007 08:31:36 +0000 Subject: (svn r11031) -Codechange: reduce the amount of duplication of bit counting functions. Based on patches by skidd13, SmatZ and Belugas. --- src/macros.h | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) (limited to 'src/macros.h') diff --git a/src/macros.h b/src/macros.h index e7944661a..4ff23c1df 100644 --- a/src/macros.h +++ b/src/macros.h @@ -420,6 +420,28 @@ static inline int KillFirstBit2x64(int value) } } +/** + * Counts the number of set bits in a variable. + * + * @param value the value to count the number of bits in. + * @return the number of bits. + */ +template static inline uint COUNTBITS(T value) +{ + uint num; + + /* This loop is only called once for every bit set by clearing the lowest + * bit in each loop. The number of bits is therefore equal to the number of + * times the loop was called. It was found at the following website: + * http://graphics.stanford.edu/~seander/bithacks.html */ + + for (num = 0; value != 0; num++) { + value &= (T)(value - 1); + } + + return num; +} + /** * Returns true if value a has only one bit set to 1 * -- cgit v1.2.3-54-g00ecf