How to remove multiple bits from a number and shift the remaining bits right to fill the gaps in C

1 Answer

0 votes
#include <stdio.h>
#include <stdlib.h>

/*
    removeBitsAndShift(number, positions, count)
    --------------------------------------------
    Removes multiple bit positions from a number and shifts the remaining bits
    right to fill the gaps.

    Important:
        Bits must be removed from highest → lowest position.
        Otherwise earlier removals shift the positions of later ones.
*/
int removeBitsAndShift(int number, const int *positions, int count) {

    // Copy and sort positions descending
    int *sorted = malloc(count * sizeof(int));
    for (int i = 0; i < count; i++) sorted[i] = positions[i];

    // Simple bubble sort descending
    for (int i = 0; i < count - 1; i++) {
        for (int j = 0; j < count - i - 1; j++) {
            if (sorted[j] < sorted[j + 1]) {
                int tmp = sorted[j];
                sorted[j] = sorted[j + 1];
                sorted[j + 1] = tmp;
            }
        }
    }

    int result = number;

    for (int i = 0; i < count; i++) {
        int pos = sorted[i];

        int left  = result >> (pos + 1);           // bits above removed bit
        int right = result & ((1 << pos) - 1);     // bits below removed bit

        result = (left << pos) | right;            // merge
    }

    free(sorted);

    return result;
}

/*
    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(" ");
    }
}

int main() {
    int number = 1234;                 // 0000 0000 0000 0000 0000 0100 1101 0010
    int positions[] = {1, 3, 7};       // remove bits 1, 3, 7 (0 = LSB)
    int count = sizeof(positions) / sizeof(positions[0]);

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

    int result = removeBitsAndShift(number, positions, count);

    printf("\n\nNumber after removing bits {1, 3, 7} and shifting remaining bits:\n");
    printBinary(result);

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

    return 0;
}



/*
run:

Original number in binary:
0000 0000 0000 0000 0000 0100 1101 0010 

Number after removing bits {1, 3, 7} and shifting remaining bits:
0000 0000 0000 0000 0000 0000 1001 0100 

Result as integer: 148

*/

 



answered 1 day ago by avibootz

Related questions

...