using System;
class ClearBitsRange
{
// Print bits of a 32-bit unsigned integer
static void PrintBits(uint x, string label) {
string bits = Convert.ToString(x, 2).PadLeft(32, '0');
Console.WriteLine($"{label}: {bits}");
}
// Clear bits in range [l, r] inclusive (0 = least significant bit)
static uint ClearBits(uint x, int l, int r) {
if (l < 0 || r > 31 || l > r)
throw new ArgumentException("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
uint 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
uint 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.
uint mask = maskLeft | maskRight;
PrintBits(mask, "mask ");
return x & mask;
}
static void Main()
{
uint value = 0b11111100111111001111110011111100;
int l = 3; // start bit
int r = 10; // end bit
uint result = ClearBits(value, l, r);
PrintBits(value, "Before ");
PrintBits(result, "After ");
}
}
/*
run:
maskLeft : 11111111111111111111100000000000
maskRight: 00000000000000000000000000000111
mask : 11111111111111111111100000000111
Before : 11111100111111001111110011111100
After : 11111100111111001111100000000100
*/