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

1 Answer

0 votes
/*
    removeBitsAndShift(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.
*/
function removeBitsAndShift(number, positions) {

    // Sort positions descending
    const sorted = [...positions].sort((a, b) => b - a);

    let result = number;

    for (const pos of sorted) {
        const left  = result >> (pos + 1);          // bits above removed bit
        const right = result & ((1 << pos) - 1);    // bits below removed bit

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

    return result;
}

/*
    printBinary(n)
    --------------
    Prints a 32-bit binary representation of an integer.
*/
function printBinary(n) {
    let binary = n.toString(2).padStart(32, "0");

    // Group into 4-bit chunks
    binary = binary.replace(/(.{4})/g, "$1 ");

    console.log(binary);
}

// Main program
const number = 1234;            // 0000 0000 0000 0000 0000 0100 1101 0010
const positions = [1, 3, 7];    // remove bits 1, 3, 7 (0 = LSB)

console.log("Original number in binary:");
printBinary(number);

const result = removeBitsAndShift(number, positions);

console.log("\nNumber after removing bits {1, 3, 7} and shifting remaining bits:");
printBinary(result);

console.log("\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 2 days ago by avibootz

Related questions

...