Replace Bit Field in a 32-bit Register

Code

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

static uint32_t make_ones_mask_u32(uint8_t len){
    if (len == 0U) {return 0U;}
    if (len >= 32U) {return 0xff;}

    return (uint32_t)((1<< len)-1U);
}

uint32_t replace_field(uint32_t reg, uint32_t val, uint8_t pos, uint8_t len) {
    // Your code here
    uint32_t ones       = make_ones_mask_u32(len);
    uint32_t field_mask = (uint32_t)(ones << pos);

    uint32_t reg_cleared = (uint32_t)(reg & ~field_mask);
    uint32_t val_shifted = (uint32_t)((val & ones) << pos);

    return (uint32_t)(reg_cleared | val_shifted);
}

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