Replace Bit Field in a 32-bit Register

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

 

 

 

Upvote
Downvote
Loading...

Input

255 0 4 4

Expected Output

15