Skip to content

Commit 37f5279

Browse files
committed
Add De Bruijn–based ctz helper
This commit introduces a De Bruijn–based count trailing zeros (ctz) helper. It provides a constant-time way to obtain the index of the lowest set bit, and can be used in future bitmap priority lookup or other bitmask-related operations.
1 parent 3d94a32 commit 37f5279

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

include/private/utils.h

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,3 +60,23 @@ static inline uint32_t nextpowerof2(uint32_t x)
6060

6161
return x;
6262
}
63+
64+
/* De-Bruijn-based count trailing zeros */
65+
inline int ctz(uint32_t v)
66+
{
67+
/* v = 0, invalid input */
68+
if (v == 0)
69+
return -1;
70+
71+
/* De-Bruijn LUT */
72+
static const uint8_t debruijn_lut[32] = {
73+
0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8,
74+
31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9};
75+
76+
/* Isolate rightmost bit */
77+
uint32_t isolated = v & (-v);
78+
79+
uint32_t hash = (isolated * 0x077CB531U) >> 27;
80+
81+
return debruijn_lut[hash & 0x1F];
82+
}

0 commit comments

Comments
 (0)