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,709 questions

55,473 answers

573 users

How to check whether only 2 bits in a number at a specific position are on (edge‑case‑safe) with Rust

1 Answer

0 votes
fn print_bits(value: u64, width: usize) {
    for i in (0..width).rev() {
        let mask = 1u64 << i;
        print!("{}", if value & mask != 0 { '1' } else { '0' });
    }
}

fn exact_bit_set(pos1: usize, pos2: usize, value: u64) -> bool {
    if pos1 >= 64 || pos2 >= 64 {
        return false;
    }
    if pos1 == pos2 {
        return false;
    }

    let mask = (1u64 << pos1) | (1u64 << pos2);

    value == mask
}

fn main() {
    let tests = [
        (0b1000010000u64, 4usize, 9usize, 10usize),
        (0b0010000010u64, 1, 7, 10),
        (0b0000100100u64, 2, 5, 10),
        (0b1000010000u64, 3, 9, 10),
        (0b1001010000u64, 4, 9, 10),
        (0b1111111111u64, 4, 9, 10),
        (0b0000000000u64, 4, 9, 10),
        (0b1000010000u64, 4, 8, 10),
        (1u64, 0, 0, 1),
        (1u64, 0, 1, 1),
        (0u64, 1, 1, 1),
    ];

    for (value, x, y, width) in tests {
        print_bits(value, width);
        print!("  bits({}, {})  ->  ", x, y);
        println!("{}", exact_bit_set(x, y, value));
    }
}



/*
OUTPUT:

1000010000  bits(4, 9)  ->  true
0010000010  bits(1, 7)  ->  true
0000100100  bits(2, 5)  ->  true
1000010000  bits(3, 9)  ->  false
1001010000  bits(4, 9)  ->  false
1111111111  bits(4, 9)  ->  false
0000000000  bits(4, 9)  ->  false
1000010000  bits(4, 8)  ->  false
1  bits(0, 0)  ->  false
1  bits(0, 1)  ->  false
0  bits(1, 1)  ->  false
   
*/

 



answered Apr 3 by avibootz
edited Apr 4 by avibootz

Related questions

...