Replace Bit Field in a 32-bit Register

 

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

uint32_t replace_field(uint32_t reg, uint32_t val, uint8_t pos, uint8_t len) {
    // Your code here
    int mask;
    int i;

    mask = 0;
    for (i=0; i < len; i++) {
        mask = (mask | (1 << (pos + i)));
    }
    mask = mask ^ 0xFFFFFFFF; // create the patch
    reg= reg & mask;          // doing AND to clear patch
    val = (val << pos);       // get the patch into place
    reg= (reg | val);		  // final value

    return reg;
}

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

 

Create a mask of all 1s except in the desired patch where it is all zeroes

then do a bitwise AND with the register to preserve all bits other than the patch

then left shift the val to position and bitwise OR it with the reg

 

Upvote
Downvote
Loading...

Input

255 0 4 4

Expected Output

15