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 <stdio.h>

/*
    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 removed bit
    int right = number & ((1 << position) - 1);    // bits below removed bit

    return (left << position) | right;             // merge shifted left + right
}

/*
    printBinary(n)
    --------------
    Prints a 32-bit binary representation of an integer.
*/
void printBinary(int n) {
    for (int i = 31; i >= 0; i--) {
        printf("%d", (n >> i) & 1);
        if (i % 4 == 0) printf(" "); // spacing for readability
    }
}

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

    printf("Original number in binary:\n");
    printBinary(number);

    int result = removeBitAndShift(number, position);

    printf("\n\nNumber after removing bit %d and shifting remaining bits:\n", position);
    printBinary(result);

    printf("\n\nResult as integer: %d\n", result);

    return 0;
}



/*
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 4 hours ago by avibootz

Related questions

1 answer 176 views
176 views asked Dec 29, 2020 by avibootz
1 answer 133 views
...