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

1 Answer

0 votes
#include <iostream>
#include <vector>
#include <bitset>
#include <algorithm>

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

    Example:
        number = 1234 (0000 0000 0000 0000 0000 0100 1101 0010)
        positions = {1, 3, 7}
*/
int removeBitsAndShift(int number, const std::vector<int>& positions) {

    // Sort positions from highest to lowest so removals don't affect earlier ones
    std::vector<int> sorted = positions;
    std::sort(sorted.begin(), sorted.end(), std::greater<int>());

    int result = number;

    for (int pos : sorted) {
        int left  = result >> (pos + 1);            // bits above removed bit
        int 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.
*/
void printBinary(int n) {
    std::bitset<32> bits(n);
    std::string s = bits.to_string();

    // Insert spaces every 4 bits
    for (int i = 0; i < 32; i++) {
        std::cout << s[i];
        if ((i + 1) % 4 == 0) std::cout << " ";
    }
}

int main() {
    int number = 1234;                     // 0000 0000 0000 0000 0000 0100 1101 0010
    std::vector<int> positions = {1, 3, 7}; // remove bits 1, 3, 7 (0 = LSB)

    std::cout << "Original number in binary:\n";
    printBinary(number);

    int result = removeBitsAndShift(number, positions);

    std::cout << "\n\nNumber after removing bits {1, 3, 7} and shifting remaining bits:\n";
    printBinary(result);

    std::cout << "\n\nResult as integer: " << result << std::endl;
}

/*
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
edited 1 day ago by avibootz

Related questions

...