How to remove every n-bit from a number 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';
}

/*
    removeEveryNthBit:
    Removes every n-th bit starting from LSB (bit 0).
    Example:
        n = 3 → remove bits 0, 3, 6, 9, ...
    Remaining bits are compacted to the right.
*/
uint32_t removeEveryNthBit(uint32_t value, uint32_t n) {
    uint32_t result = 0;      // Holds the compacted output bits
    uint32_t writePos = 0;    // Next position to write a kept bit into 'result'
 
    for (uint32_t readPos = 0; readPos < 32; ++readPos) {

        // Determine whether this bit should be removed.
        // We remove bits at positions: 0, n, 2n, 3n, ...
        int remove = (readPos % n == 0);

        // Extract the bit at position readPos from 'value'
        uint32_t bit = (value >> readPos) & 1u;
 
        // If the bit is NOT removed, pack it into the next free position
        if (!remove) {
            result |= (bit << writePos);   // Write the bit into the compacted result
            ++writePos;                    // Advance the write position
        }
    }

    // Return the compacted bitstream
    return result;
}

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

    uint32_t result = removeEveryNthBit(value, n);

    std::cout << "\nAfter removing every " << n << "-th bit:\n";
    printBinary(result);

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

int main() {
    uint32_t number = 498980827;
    uint32_t n = 3;   // dynamic: change this to any n you want

    zero_bits_every_step(number, n);
}


/*
run:

Original number: 498980827
00011101101111011101011111011011

After removing every 3-th bit:
00000000000001101011011001110101
Result value: 439925

*/

 



answered 1 day ago by avibootz
edited 1 day ago by avibootz

Related questions

...