Find first 1 or 0 bit in an unsigned value

In C++, this is __builtin_ffs(int x) Most modern CPUs have this built in. Does Rust have an equivalent?

__builtin_ffs
Returns one plus the index of the least significant 1-bit of x, or if x is zero, returns zero.

Sounds mostly like trailing_zeroes and trailing_ones, give or take some bit-twiddling.

Alternatively, on nightly, you can call architecture-specific instructions like _mm_tzcnt_32 through the std::arch module

2 Likes

There are many intrinsics available for counting leading zeros, all architecture-specific.

bitvec::BitSlice has first_one() and first_zero() methods: BitSlice in bitvec::slice - Rust