Uncle Intel has two built-in instructions, CLZ and BSR, which stand for Count Leading Zeros and Bit Reverse Scan. They give you, respectively, the number of leading zeros of a number and the index of the first 1 in its bit representation.
One neat use for them is floor(log2(n)): instead of actually computing it, you can get it with nothing more than clz and an add/sub:
floor(log2(n)) = sizeof(n) - 1 - clz(n)
GCC has a function, __builtin_clz, that does this, and Rust has leading_zeros (and its little brother, leading_ones). For example, to get the floor of the log in Rust, you could write a function like this:
use num::PrimInt;
fn log2<T: PrimInt>(n: T) -> usize {
(size_of::<T>() << 3) - n.leading_zeros() as usize - 1
}
Then again, it looks like Rust itself also has an ilog2 function that does exactly this:
pub const fn ilog2(self) -> u32 {
if let Some(log) = self.checked_ilog2() {
log
} else {
int_log10::panic_for_nonpositive_argument()
}
}
pub const fn checked_ilog2(self) -> Option<u32> {
if self <= 0 {
None
} else {
// SAFETY: We just checked that this number is positive
let log = (Self::BITS - 1) - unsafe { intrinsics::ctlz_nonzero(self) as u32 };
Some(log)
}
}