Skip to content

Commit f6176a3

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 f6176a3

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

include/lib/libc.h

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -153,3 +153,23 @@ char *getline(char *s);
153153
int32_t printf(const char *fmt, ...);
154154
int32_t snprintf(char *str, size_t size, const char *fmt, ...);
155155
int vsnprintf(char *str, size_t size, const char *fmt, va_list args);
156+
157+
/* De-Bruijn-based count trailing zeros */
158+
inline int ctz(uint32_t v)
159+
{
160+
/* v = 0, invalid input */
161+
if (v == 0)
162+
return -1;
163+
164+
/* De-Bruijn LUT */
165+
static const uint8_t debruijn_lut[32] = {
166+
0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8,
167+
31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9};
168+
169+
/* Isolate rightmost bit */
170+
uint32_t isolated = v & (-v);
171+
172+
uint32_t hash = (isolated * 0x077CB531U) >> 27;
173+
174+
return debruijn_lut[hash & 0x1F];
175+
}

0 commit comments

Comments
 (0)