]> git.buserror.net Git - polintos/scott/priv.git/blobdiff - include/c/lowlevel/bitops.h
Use GCC builtins for bit scanning. The minor benefit is that it is
[polintos/scott/priv.git] / include / c / lowlevel / bitops.h
index 9c3ce7e17f6d07b5af44063915281173e6995803..6aa90292b3bdcc3fb1d8e9542da8d6b830f70d4b 100644 (file)
@@ -7,9 +7,39 @@
 #include <lowlevel/types.h>
 #include _LL_INC(bitops.h)
 
+// Find First (least-significant) Set, counting from 0,
+// undefined if no bits set
+
+static inline int ll_ffs(unsigned long val)
+{
+       return __builtin_ctzl(val);
+}
+
+// Find Last (most-significant) Set, counting from 0, 
+// undefined if no bits set
+
+static inline int ll_fls(unsigned long val)
+{
+       return (sizeof(unsigned long)*8 - 1) ^ __builtin_clzl(val);
+}
+
+// As above, except on 64-bit values regardless of sizeof(long).
+static inline int ll_ffs64(uint64_t val)
+{
+       return __builtin_ctzll(val);
+}
+
+// Find Last (most-significant) Set, counting from 0, 
+// undefined if no bits set
+
+static inline int ll_fls64(unsigned long val)
+{
+       return (sizeof(unsigned long long)*8 - 1) ^ __builtin_clzll(val);
+}
+
 static inline int ll_get_order_round_up(unsigned long val)
 {
-       return val != 1 ? ll_fls(val - 1) + 1 : 0;
+       return val > 1 ? ll_fls(val - 1) + 1 : 0;
 }
 
 static inline int ll_get_order_round_down(unsigned long val)