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

    // Mask is created by creating 1s up until the desired length
    // and shifting them into position.
    uint32_t mask = ((1U << len) - 1) << pos; 

    // Register is OR'd to set bits
    return reg | mask;
}

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

I looked into the solution and found it very clever. The logic is that every power 2 to the nth power subtracted by 1 results in a binary that is all ones. 

For example, 8 = 1000 while 7 = 111. This trend stays the same for all 2 to the nth power. 

Lastly, the resulting binary is then shifted into the appropriate position by pos, which completes the mask.  

Upvote
Downvote
Loading...

Input

0 4 3

Expected Output

112