How to clear bits in the given range in C

1 Answer

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

/* Print bits of a 32-bit integer */
void printBits(uint32_t x, const char *label) {
    int i;
    printf("%s: ", label);
    for (i = 31; i >= 0; --i) {
        printf("%u", (x >> i) & 1u);
    }
    printf("\n");
}

/* Clear bits in range [l, r] inclusive (0 = least significant bit) */
uint32_t clearBits(uint32_t x, int l, int r) {
    if (l < 0 || r > 31 || l > r) {
        fprintf(stderr, "Invalid bit range\n");
        exit(EXIT_FAILURE);
    }

    /* maskLeft:
       Create a mask with 1s above bit r and 0s from bit r down to 0.
       Example: r = 5 → maskLeft = 11111111 11111111 11111111 11000000
    */
    uint32_t maskLeft = ~0u << (r + 1);
    printBits(maskLeft, "maskLeft ");

    /* maskRight:
       Create a mask with 1s below bit l and 0s from bit l upward.
       Example: l = 3 → maskRight = 00000000 00000000 00000000 00000111
    */
    uint32_t maskRight = (1u << l) - 1;
    printBits(maskRight, "maskRight");

    /* Combine both masks:
       maskLeft keeps bits above r.
       maskRight keeps bits below l.
       The range [l, r] becomes 0s.
    */
    uint32_t mask = maskLeft | maskRight;
    printBits(mask, "mask     ");

    return x & mask;
}

int main(void) {
    uint32_t value = 0b11111100111111001111110011111100;
    int l = 3;   /* start bit */
    int r = 10;  /* end bit */

    uint32_t result = clearBits(value, l, r);

    printBits(value, "Before   ");
    printBits(result, "After    ");

    return 0;
}


/*
run:

maskLeft : 11111111111111111111100000000000
maskRight: 00000000000000000000000000000111
mask     : 11111111111111111111100000000111
Before   : 11111100111111001111110011111100
After    : 11111100111111001111100000000100

*/

 



answered Dec 29, 2025 by avibootz
...