uint32_t set_bits(uint32_t reg, uint8_t pos, uint8_t len) {
// If pos is outside 0–31, do nothing
if (pos >= 32)
return reg;
// If len is zero, nothing to set
if (len == 0)
return reg;
// Clamp len so we don't exceed 32-bit width
if (pos + len > 32)
len = 32 - pos;
// Create mask safely
uint32_t mask = ((1u << len) - 1u) << pos;
return reg | mask;
}