21. Replace Bit Field in a 32-bit Register

Back To All Submissions
Previous Submission
Next Submission

Code

#include <stdio.h>
#include <stdint.h>

uint32_t replace_field(uint32_t reg, uint32_t val, uint8_t pos, uint8_t len) {
    // Your code here
    // Clear bits at the specified field first
    uint32_t bitmask = ~(((1 << len) - 1) << pos);
    reg &= bitmask;
    // replace bits
    reg |= (val << pos);
    return reg;
}

int main() {
    uint32_t reg, val;
    uint8_t pos, len;
    scanf("%u %u %hhu %hhu", &reg, &val, &pos, &len);
    printf("%u", replace_field(reg, val, pos, len));
    return 0;
}

Solving Approach

First, we must clear the bits from pos to pos + len -1, using an inverse mask and a & operator.

Then, we can proceed to replace the bits with val left shifted to pos.

 

 

Was this helpful?
Upvote
Downvote