Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,703 questions

55,462 answers

573 users

How to clear bits in the given range in Rust

1 Answer

0 votes
// Print bits of a 32-bit integer
fn print_bits(x: u32, label: &str) {
    // Print as 32-bit binary with leading zeros
    println!("{}: {:032b}", label, x);
}

// Clear bits in range [l, r] inclusive (0 = least significant bit)
fn clear_bits(x: u32, l: i32, r: i32) -> u32 {
    if l < 0 || r > 31 || l > r {
        panic!("Invalid bit range");
    }

    // maskLeft:
    // Create a mask with 1s above bit r and 0s from bit r down to 0.
    // Example: r = 5 → maskLeft = 11111111 11111111 11111111 11000000
    let mask_left: u32 = (!0u32) << (r + 1);
    print_bits(mask_left, "maskLeft ");

    // maskRight:
    // Create a mask with 1s below bit l and 0s from bit l upward.
    // Example: l = 3 → maskRight = 00000000 00000000 00000000 00000111
    let mask_right: u32 = (1u32 << l) - 1;
    print_bits(mask_right, "maskRight");

    // Combine both masks:
    // maskLeft keeps bits above r.
    // maskRight keeps bits below l.
    // The range [l, r] becomes 0s.
    let mask: u32 = mask_left | mask_right;
    print_bits(mask, "mask     ");

    x & mask
}

fn main() {
    let value: u32 = 0b11111100111111001111110011111100;

    let l = 3;   // start bit
    let r = 10;  // end bit

    let result = clear_bits(value, l, r);

    print_bits(value,  "Before   ");
    print_bits(result, "After    ");
}




/*
run:

maskLeft : 11111111111111111111100000000000
maskRight: 00000000000000000000000000000111
mask     : 11111111111111111111100000000111
Before   : 11111100111111001111110011111100
After    : 11111100111111001111100000000100

*/

 



answered Dec 30, 2025 by avibootz
...