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

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

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,844 questions

55,671 answers

573 users

How to remove a bit from a number and shift all bits to the right to fill the gap in C++

1 Answer

0 votes
#include <iostream>

/*
    removeBitAndShift(number, position)
    -----------------------------------
    Removes the bit at the given position and shifts all higher bits right.

    Example:
        number = 22 (10110)
        position = 2 (0 = LSB)

        Bits: 1 0 1 1 0
                  ^ remove this bit (bit 2)

        Split:
            left  = bits above the removed bit  (bits 3..31)
            right = bits below the removed bit  (bits 0..1)

        left << position   moves the left part down by one bit
        result = (left << position) | right
*/
int removeBitAndShift(int number, int position) {
    int left  = number >> (position + 1);   // bits above the removed bit
    int right = number & ((1 << position) - 1); // bits below the removed bit

    return (left << position) | right;      // shift left part right, merge
}

/*
    printBinary(n)
    --------------
    Prints a 32-bit binary representation of an integer.
*/
void printBinary(int n) {
    for (int i = 31; i >= 0; i--) {
        std::cout << ((n >> i) & 1);
        if (i % 4 == 0) std::cout << " ";
    }
}

int main() {
    int number = 22, position = 2; //  (0 = LSB)

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

    int result = removeBitAndShift(number, position);

    std::cout << "\n\nNumber after removing bit " << position 
         << " 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 0000 0001 0110 

Number after removing bit 2 and shifting remaining bits:
0000 0000 0000 0000 0000 0000 0000 1010 

Result as integer: 10

*/

 



answered Jun 23 by avibootz
edited Jun 23 by avibootz

Related questions

...