How do you set all bits in a range from position l to r?
Short answer: Build a mask of ones from bit l to bit r and OR it in. With 0-based positions: mask = ((1u << (r - l + 1)) - 1u) << l, valid while the field is narrower than 32 bits.
#include <stdint.h>
/* 0-based, inclusive: l <= r <= 31 */
uint32_t range_mask(unsigned l, unsigned r)
{
unsigned width = r - l + 1;
uint32_t ones = (width >= 32) ? 0xFFFFFFFFu : ((1u << width) - 1u);
return ones << l;
}
uint32_t set_range(uint32_t x, unsigned l, unsigned r) { return x | range_mask(l, r); }
uint32_t clear_range(uint32_t x, unsigned l, unsigned r) { return x & ~range_mask(l, r); }
uint32_t toggle_range(uint32_t x, unsigned l, unsigned r) { return x ^ range_mask(l, r); }
Example: l = 3, r = 4 (0-based) → width 2 → 0b11 << 3 = 0b0001_1000 = 24.
The XOR form (1-based positions). A version often seen in practice:
int l = 4, r = 5; /* 1-based positions */
unsigned mask = ((1u << (l - 1)) - 1u) ^ ((1u << r) - 1u);
/* (1<<3)-1 = 0b00111, (1<<5)-1 = 0b11111, XOR = 0b11000 = 24 */
(1 << r) - 1 is ones in positions 1..r, and (1 << (l-1)) - 1 is ones in positions 1..l-1. XOR removes the lower ones, leaving positions l..r. It is correct, but it breaks for r = 32 (1u << 32 is undefined), and it is easy to confuse 1-based and 0-based positions. State which you mean before you write code.
Kernel-style GENMASK avoids the overflow by shifting all-ones instead:
#define GENMASK(h, l) (((~0u) << (l)) & (~0u >> (31 - (h)))) /* 0-based, h >= l */
Follow-up: "Check whether all bits in the range are set": (x & mask) == mask. "Any bit set?": (x & mask) != 0.