From abe5949cd2562f9f5c2a0af8460c675c069e28a2 Mon Sep 17 00:00:00 2001 From: Benjamin Valentin Date: Tue, 23 May 2023 15:55:43 +0200 Subject: [PATCH] core/bitarithm: add bitarithm_clzb() --- core/lib/include/bitarithm.h | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/core/lib/include/bitarithm.h b/core/lib/include/bitarithm.h index f02cfcc51d..ac2a88c402 100644 --- a/core/lib/include/bitarithm.h +++ b/core/lib/include/bitarithm.h @@ -165,6 +165,30 @@ static inline unsigned bitarithm_msb(unsigned v) #endif } +/** + * @brief Returns the number of leading 0-bits in @p x, starting at the most + * significant bit position. + * If x is 0, the result is undefined. + * + * @param[in] x Input value + * @return Number of leading zero bits + */ +static inline uint8_t bitarithm_clzb(uint8_t x) +{ +#if defined(BITARITHM_HAS_CLZ) + /* clz operates on `unsigned int`, so `x` will be promoted to the size + of an `unsigned int` */ + return __builtin_clz(x) - 8 * (sizeof(unsigned) - 1); +#else + uint8_t l = 0; + while (!(x & 0x80)) { + ++l; + x <<= 1; + } + return l; +#endif +} + /** * @private *