How to remove every n-bit from a number and shift the remaining bits right in C

1 Answer

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

/*
    printBinary:
    Prints a 32‑bit binary representation of an unsigned integer.
*/
void printBinary(uint32_t value) {
    for (int i = 31; i >= 0; --i) {
        putchar((value & (1u << i)) ? '1' : '0');
    }
    putchar('\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 after removal
    uint32_t writePos = 0;    // Next bit position to write into in '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;                    // Move to the next output bit position
        }
    }

    // Return the compacted bitstream after all removals
    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) {
    printf("Original number: %u\n", value);
    printBinary(value);

    uint32_t result = removeEveryNthBit(value, n);

    printf("\nAfter removing every %u-th bit:\n", n);
    printBinary(result);

    printf("Result value: %u\n", result);
}

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

    zero_bits_every_step(number, n);

    return 0;
}



/*
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

...