How to clear bits in the given range in C++

2 Answers

0 votes
#include <iostream>
#include <bitset>
#include <cstdint>
 
// Print bits of a 32-bit integer
void printBits(uint32_t x, const std::string& label) {
    std::cout << label << ": " << std::bitset<32>(x) << "\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) {
        throw std::invalid_argument("Invalid bit range");
    }
 
    // 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() {
    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    ");
}
 
  
  
/*
run:
  
maskLeft : 11111111111111111111100000000000
maskRight: 00000000000000000000000000000111
mask     : 11111111111111111111100000000111
Before   : 11111100111111001111110011111100
After    : 11111100111111001111100000000100
  
*/


 



answered Dec 28, 2025 by avibootz
edited Dec 28, 2025 by avibootz
0 votes
#include <iostream>
#include <bitset>
#include <cstdint>

// Print bits of a 32-bit integer
void printBits(uint32_t x, const std::string& label) {
    std::cout << label << ": " << std::bitset<32>(x) << "\n";
}

// Clear a single bit at position i (0 = least significant bit)
uint32_t clearBit(uint32_t value, int i) {
    uint32_t mask = ~(1u << i);
    
    return value & mask;
}

// Clear bits in the inclusive range [l, r]
uint32_t clearBitRange(uint32_t value, int l, int r) {
    if (l < 0 || r > 31 || l > r) {
        throw std::invalid_argument("Invalid bit range");
    }

    for (int i = l; i <= r; i++) {
        value = clearBit(value, i);
    }
    
    return value;
}

int main() {
    uint32_t value = 0b11111100111111001111110011111100;

    int l = 3;   // start bit
    int r = 10;  // end bit

    printBits(value, "Before");

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

    printBits(result, "After ");

    return 0;
}

 
 
/*
run:

Before: 11111100111111001111110011111100
After : 11111100111111001111100000000100
 
*/

 



answered Dec 28, 2025 by avibootz
...