From: Pavel Charvat Date: Sat, 17 Nov 2012 17:38:27 +0000 (+0100) Subject: Bitops: Implement bit_count() X-Git-Tag: v5.99~92 X-Git-Url: http://mj.ucw.cz/gitweb/?a=commitdiff_plain;h=c9fb656c941e56824590c15a5159a5ce8596a938;p=libucw.git Bitops: Implement bit_count() --- diff --git a/ucw/bitops.h b/ucw/bitops.h index c1e63710..9e5e5df8 100644 --- a/ucw/bitops.h +++ b/ucw/bitops.h @@ -2,6 +2,7 @@ * UCW Library -- Bit Operations * * (c) 2005 Martin Mares + * (c) 2012 Pavel Charvat * * This software may be freely distributed and used according to the terms * of the GNU Lesser General Public License. @@ -37,4 +38,28 @@ static inline uns bit_ffs(uns w) #endif +/* Count the number of bits set */ + +#if __GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) + +static inline uns bit_count(uns w) +{ + return __builtin_popcount(w); +} + +#else + +static inline uns bit_count(uns w) +{ + uns n = 0; + while (w) + { + w &= w - 1; + n++; + } + return n; +} + +#endif + #endif