[Mesa-dev] [PATCH 1/2] util: Add util_is_power_of_two_minus_one

Alyssa Rosenzweig alyssa.rosenzweig at collabora.com
Fri Jun 14 16:42:36 UTC 2019


Checks if a number is one less than a power of two. Equivalently, this
checks if a number is all ones in binary. The latter definition is
helpful in the context of masks.

The function is trivial; this is *the* canonical check and is
arguably no less clean than calling util_is_power_of_two(x + 1) (the
latter function implemented similarly). Still, it's worth having a
dedicated check for this; semantically, in the context of masks, this
check is meaningful standalone, justifying an independent implementation
from the existing util_is_power_of_two* utilites.

Signed-off-by: Alyssa Rosenzweig <alyssa.rosenzweig at collabora.com>
Cc: Ian Romanick <ian.d.romanick at intel.com>
Cc: Eduardo Lima Mitev <elima at igalia.com>
---
 src/util/bitscan.h | 9 +++++++++
 1 file changed, 9 insertions(+)

diff --git a/src/util/bitscan.h b/src/util/bitscan.h
index dc89ac93f28..632f7dd2e67 100644
--- a/src/util/bitscan.h
+++ b/src/util/bitscan.h
@@ -158,6 +158,15 @@ util_is_power_of_two_nonzero(unsigned v)
 #endif
 }
 
+/* Determine if an unsigned value is one less than a power-of-two
+ */
+
+static inline bool
+util_is_power_of_two_minus_one(unsigned v)
+{
+   return (v & (v + 1)) == 0;
+}
+
 /* For looping over a bitmask when you want to loop over consecutive bits
  * manually, for example:
  *
-- 
2.20.1



More information about the mesa-dev mailing list