21. Replace Bit Field in a 32-bit Register

Back To All Submissions
Previous Submission
Next Submission

Code

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

int main() {
    uint32_t reg, val;
    int pos, len;

    scanf("%u", &reg);
    scanf("%u", &val);
    scanf("%d", &pos);
    scanf("%d", &len);

    uint32_t mask = ((1U << len) - 1) << pos;
    reg = (reg & ~mask) | ((val << pos) & mask);

    printf("%u", reg);
    return 0;
}

Solving Approach

 

 

 

Was this helpful?
Upvote
Downvote