How to remove multiple bits from a number and shift the remaining bits right to fill the gaps in Rust

1 Answer

0 votes
/*
    remove_bits_and_shift(number, positions)
    ----------------------------------------
    Removes multiple bit positions from a number and shifts the remaining bits
    right to fill the gaps.

    Important:
        Bits must be removed from highest → lowest position.
        Otherwise earlier removals shift the positions of later ones.
*/
fn remove_bits_and_shift(number: i32, positions: &[i32]) -> i32 {
    // Sort positions descending
    let mut sorted: Vec<i32> = positions.to_vec();
    sorted.sort_by(|a, b| b.cmp(a));

    let mut result: i32 = number;

    for &pos in &sorted {
        let left: i32  = result >> (pos + 1);          // bits above removed bit
        let right: i32 = result & ((1 << pos) - 1);    // bits below removed bit

        result = (left << pos) | right;                // merge
    }

    result
}

/*
    print_binary(n)
    ---------------
    Prints a 32-bit binary representation of an integer.
*/
fn print_binary(n: i32) {
    let binary: String = format!("{:032b}", n);
    let grouped: String = binary
        .as_bytes()
        .chunks(4)
        .map(|chunk| std::str::from_utf8(chunk).unwrap())
        .collect::<Vec<&str>>()
        .join(" ");

    println!("{}", grouped);
}

fn main() {
    let number: i32 = 1234;           // 0000 0000 0000 0000 0000 0100 1101 0010
    let positions: [i32; 3] = [1, 3, 7]; // remove bits 1, 3, 7 (0 = LSB)

    println!("Original number in binary:");
    print_binary(number);

    let result: i32 = remove_bits_and_shift(number, &positions);

    println!("\nNumber after removing bits {{1, 3, 7}} and shifting remaining bits:");
    print_binary(result);

    println!("\nResult as integer: {}", result);
}



/*
run:

Original number in binary:
0000 0000 0000 0000 0000 0100 1101 0010

Number after removing bits {1, 3, 7} and shifting remaining bits:
0000 0000 0000 0000 0000 0000 1001 0100

Result as integer: 148

*/

 



answered 1 day ago by avibootz

Related questions

...