How to remove bits at specific positions and shift the remaining bits right in C++

1 Answer

0 votes
#include <iostream>
#include <bitset>
#include <cstdint>

/*
    printBinary:
    Prints a 32‑bit binary representation of an unsigned integer.
*/
void printBinary(uint32_t value) {
    std::cout << std::bitset<32>(value) << '\n';
}

/*
    removeSpecificPositions:
    Removes bits at positions:
    0,3,6,9,12,15,18,21,24,27,30   (LSB = position 0)

    All remaining bits are compacted to the right.
*/
uint32_t removeSpecificPositions(uint32_t value) {
    uint32_t result = 0;
    uint32_t writePos = 0;

    for (uint32_t readPos = 0; readPos < 32; ++readPos) {
        bool remove =
            (readPos == 0  || readPos == 3  || readPos == 6  ||
             readPos == 9  || readPos == 12 || readPos == 15 ||
             readPos == 18 || readPos == 21 || readPos == 24 ||
             readPos == 27 || readPos == 30);

        uint32_t bit = (value >> readPos) & 1u;

        if (!remove) {
            result |= (bit << writePos);
            ++writePos;
        }
    }
    return result;
}

/*
    zero_bits_every_step:
    Shows the number before and after removing the selected bit positions.
*/
void zero_bits_every_step(uint32_t value) {
    std::cout << "Original number: " << value << "\n";
    printBinary(value);

    uint32_t result = removeSpecificPositions(value);

    std::cout << "\nAfter removing bits at positions "
                 "0,3,6,9,12,15,18,21,24,27,30:\n";
    printBinary(result);

    std::cout << "Result value: " << result << "\n";
}

int main() {
    uint32_t number = 498980827;

    zero_bits_every_step(number);
}



/*
run:

Original number: 498980827
00011101101111011101011111011011

After removing bits at positions 0,3,6,9,12,15,18,21,24,27,30:
00000000000001101011011001110101

Result value: 439925

*/

 



answered 1 day ago by avibootz

Related questions

...