Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,699 questions

57,016 answers

573 users

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 Jun 25 by avibootz
edited Jun 25 by avibootz

Related questions

...