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) {
    // Your code here
    reg |= (((1 << len) - 1) << pos);
    return reg;
    
}


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

Let's use an example where:

  • Register (reg): 128 (We'll just look at the lowest 8 bits for easy reading: 10000000)
  • Position (pos): 2
  • Length (len): 3

We want to Set 3 switches ON, starting at Index 2. This means we need to force the switches at Index 2, 3, and 4 to be ON.

Step 1: Making a "Block of 1s" ((1 << len) - 1)

Instead of a single pointer, we need a block of 1s equal to our length. There is a clever mathematical trick for this in C:

  1. First, take 1 and shift it by len (3). (1 << 3) gives us 00001000 (which is 8).
  2. Then, subtract 1. 8 - 1 = 7.
  3. The binary for 7 is 00000111.

Look at that! By doing ((1 << len) - 1), we magically generated exactly three 1s packed together on the far right.

Step 2: Shifting the Block into Position

Now we have our block of switches (00000111), but they are at the very beginning (indexes 0, 1, 2). We need them to start at pos (Index 2).

We take our block and shift it left by pos:

  • 00000111 << 2 becomes 00011100.

This is our final Mask. It has exactly three 1s, starting right at Index 2.

Step 3: The "Set" Command (|)

Just like setting a single bit, we use the Bitwise OR (|) operator because it acts as a forceful "ON" button without turning anything off.

Your final C code to do this in one line is: reg |= (((1 << len) - 1) << pos);

 

 

Upvote
Downvote
Loading...

Input

0 4 3

Expected Output

112