]> mj.ucw.cz Git - libucw.git/commitdiff
Bitops: Implement bit_count()
authorPavel Charvat <pchar@ucw.cz>
Sat, 17 Nov 2012 17:38:27 +0000 (18:38 +0100)
committerMartin Mares <mj@ucw.cz>
Sat, 17 Nov 2012 17:39:03 +0000 (18:39 +0100)
ucw/bitops.h

index c1e6371027a5d39e6fef6dca8883af6e8f922280..9e5e5df8b2be75761bcf70cd7e425860d6f62f52 100644 (file)
@@ -2,6 +2,7 @@
  *     UCW Library -- Bit Operations
  *
  *     (c) 2005 Martin Mares <mj@ucw.cz>
+ *     (c) 2012 Pavel Charvat <pchar@ucw.cz>
  *
  *     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