Replace Bit Field in a 32-bit Register

Code

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

uint32_t replace_field(uint32_t reg, uint32_t val, uint8_t pos, uint8_t len) {
    // 1. Create a mask of 'len' ones (e.g., if len=4, mask=0xF)
    uint32_t mask = (1U << len) - 1;
    
    // 2. Clear the target bits in the register:
    // Move the mask to 'pos', invert it, then AND it with the register.
    reg &= ~(mask << pos);
    
    // 3. Mask the input value to ensure it fits, shift it to 'pos',
    // then OR it into the register.
    reg |= ((val & mask) << pos);
    
    return reg;
}

int main() {
    uint32_t reg, val;
    uint8_t pos, len;
    // Note: Using %u for uint32_t and %hhu for uint8_t
    if (scanf("%u %u %hhu %hhu", &reg, &val, &pos, &len) == 4) {
        printf("%u\n", replace_field(reg, val, pos, len));
    }
    return 0;
}

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

255 0 4 4

Expected Output

15