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) {
    // Create a base mask
    uint32_t base_mask = (1U << len) - 1;
    
    //Clear the bits at the target position
    // Shift the mask to the position, invert it (~), and AND
    reg &= ~(base_mask << pos);

    // 3. Prepare the new value
    // (new_val & base_mask): Safety step! Truncates value if it's too big.
    // << pos: Shifts the value to the correct slot.
    uint32_t prepared_value = (val & base_mask) << pos;

    // 4. Combine (OR) the cleaned register with the new valu 
    return reg | prepared_value;
}

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

 

 

 

Upvote
Downvote
Loading...

Input

255 0 4 4

Expected Output

15