#include <stdio.h>
#include <stdint.h>
uint32_t set_bits(uint32_t reg, uint8_t pos, uint8_t len) {
return reg | (((1U<<len)-1)<<pos);
}
int main() {
uint32_t reg;
uint8_t pos, len;
scanf("%u %hhu %hhu", ®, &pos, &len);
printf("%u", set_bits(reg, pos, len));
return 0;
}Set len consecutive bits starting from position pos
Without affecting other bits.
len number of 1’s(1U << len) - 1
Why?
If len = 3:
1U << 3 → 00001000
Minus 1 → 00000111
Now we have len ones.
pos((1U << len) - 1) << pos
Moves the 1’s to correct location.
Example:
pos = 4
len = 3
Mask = 00000111 << 4
= 01110000
reg | mask
Why OR?
return reg | (((1U << len) - 1) << pos);
✔ Generates block mask
✔ Positions it correctly
✔ Sets only required bits
✔ Embedded-safe
✔ Interview-ready
Input
0 4 3
Expected Output
112