Set Specific Bits in a 32-bit Register

Code

#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", &reg, &pos, &len);
    printf("%u", set_bits(reg, pos, len));
    return 0;
}

Solving Approach

✅ Set Multiple Bits — Compact Approach

🎯 Goal

Set len consecutive bits starting from position pos
Without affecting other bits.

1️⃣ Create len number of 1’s

(1U << len) - 1

Why?

If len = 3:

1U << 3  →  00001000
Minus 1  →  00000111

Now we have len ones.

2️⃣ Shift the block to position pos

((1U << len) - 1) << pos

Moves the 1’s to correct location.

Example:

pos = 4
len = 3
Mask = 00000111 << 4
      = 01110000

3️⃣ OR with register

reg | mask

Why OR?

  • Forces selected bits to 1
  • Leaves other bits unchanged

💡 Final One-Line Logic

return reg | (((1U << len) - 1) << pos);

✔ Generates block mask
✔ Positions it correctly
✔ Sets only required bits
✔ Embedded-safe
✔ Interview-ready

 

 

Upvote
Downvote
Loading...

Input

0 4 3

Expected Output

112