How to set specific bits and find the set bits indexes in Rust

1 Answer

0 votes
const BIT_SIZE: usize = 16;

// Print binary representation of the bits
fn print_binary(bits: u16) {
    println!("{:016b}", bits);
}

// Find the first set bit (least significant)
fn find_first_set_bit(bits: u16) -> Option<usize> {
    for i in 0..BIT_SIZE {
        if bits & (1 << i) != 0 {
            return Some(i);
        }
    }
    None
}

fn print_set_bit_indexes(bits: u16) {
    for i in 0..BIT_SIZE {
        if bits & (1 << i) != 0 {
            print!("{} ", i);
        }
    }
    println!();
}

fn main() {
    let mut bits: u16 = 0;
    bits |= 1 << 3;
    bits |= 1 << 5;
    bits |= 1 << 11;
    bits |= 1 << 14;

    print_binary(bits);

    match find_first_set_bit(bits) {
        Some(index) => println!("First set bit at index: {}", index),
        None => println!("No bits are set."),
    }

    println!("All the set bits indexes:");
    print_set_bit_indexes(bits);
}



/*
run:

0100100000101000
First set bit at index: 3
All the set bits indexes:
3 5 11 14 

*/

 



answered Nov 4, 2025 by avibootz
...