Log of power of two

Hello,

I have an usize which is a power of two. So, its binary representation is something like 00...01000...0. Is there a way to have the log2 of that number without converting to a floating number first? That is, I would like to find the position of the 1 in the binary representation.

You can use leading_zeros to find the position of the first 1 in the binary representation:

fn log2(x: u64) -> u32 {
    debug_assert!(x > 0, "can't compute log of zero");
    63 - x.leading_zeros()
}
4 Likes

If your input is guaranteed to be a power of 2, you could use trailing_zeros:

fn log2(x: u64) -> u32 {
    debug_assert_eq!(x.count_ones(), 1, "x must be a power of 2");
    x.trailing_zeros()
}
3 Likes

Awesome thanks!

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.