How do you find the position of the most significant bit (MSB) of an unsigned integer in Rust

1 Answer

0 votes
/// Returns the zero-based position of the most significant set bit (MSB)
/// in an unsigned 32-bit integer.
///
/// Examples:
///     1  -> Some(0)
///     2  -> Some(1)
///     8  -> Some(3)
///     15 -> Some(3)
///
/// Returns:
///     None if the value is 0 because no bits are set.
fn msb_position(value: u32) -> Option<u32> {
    if value == 0 {
        return None;
    }

    Some(u32::BITS - 1 - value.leading_zeros())
}

fn main() {
    let test_values: [u32; 7] = [
        0,
        1,
        2,
        8,
        15,
        0x1234,
        0x8000_0000,
    ];

    for value in test_values {
        match msb_position(value) {
            Some(position) => {
                println!(
                    "Value: {}, MSB position: {}",
                    value, position
                );
            }
            None => {
                println!(
                    "Value: {}, no bits are set",
                    value
                );
            }
        }
    }
}



/*
run:

Value: 0, no bits are set
Value: 1, MSB position: 0
Value: 2, MSB position: 1
Value: 8, MSB position: 3
Value: 15, MSB position: 3
Value: 4660, MSB position: 12
Value: 2147483648, MSB position: 31

*/

 



answered Oct 1 by avibootz
...