Replace Bit Field in a 32-bit Register

Code

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

void printBinary(uint32_t x);

uint32_t replace_field(uint32_t reg, uint32_t val, uint8_t pos, uint8_t len) {
    // Your code here
    //1. Create mask for bits to replace
    //1.1 Put first bit at len (e.g 4)
    //mask = 1 << len (0001 0000)
    //1.2 Subtract 1 to get mask of 1s for length
    //mask = (1 << len)-1 (0000 1111)
    //2 Shift mask into correct position
    //mask = ((1<<len)-1 << pos) (1111 0000)
    //3. Flip the mask to set other mask bits to 1 (keeps rest of untargeted bits unchanged)
    //mask = ~((1<<len)-1 << pos) (0000 1111)
    //4. Combine reg &= mask to clear bits that were where the mask was  
    uint32_t mask = ((1U << len)-1) << pos;
    reg &= ~mask; //(normal reg with 000 where mask was) (0000 0000)
    
    //5. Create a new 1's mask & put it where you want to insert the new value
    //(1U << len)-1 (0000 0110) *new value mask
    //5.1 & with the new value to set the mask to the correct bits
    // (val & (1U << len)-1)  (0000 0100) * correct value bits
    //5.2 shift bits into correct position & OR with register to update reg
    reg |= (val & ((1U << len)-1)) << pos;

    // printf("Mask\n");
    // printBinary(mask);
    // printf("Inverted Mask\n");
    // printBinary(~mask); //(1111 1111 0000 1111 1111)
    // printf("Reg\n");
    // printBinary(reg);
    // printf("original reg &= ~mask reg with target fields cleared\n");
    // printBinary(reg &= ~mask);
    // printf("New value\n");
    // printBinary(val);
    // printf("New value & mask\n");
    // printBinary((val & ((1U << len)-1)) << pos);
    // printf("New reg value\n");
    // printBinary(reg |= (val & ((1U << len)-1)) << pos);

    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;
}

//FUNCTION TO PRINT BINARY 8 bit
void printBinary(uint32_t x){
    //1. Find size of passed int
    int num_bits = sizeof(x)*8;
    //2. loop through every bit and perform checkbit
    //printf("Int value is: %hhu, Num of bits is: %d\n",x, num_bits);
    for(int i=num_bits-1;i>=0;i--){
    //Prints a space every 4 bits
    if ((i+1)%4==0 && i+1 != sizeof(x)*8){
        printf(" ");
    }
    if (x & (1 << i)){
        printf("1");
    } 
    else{
        printf("0");
    }
    }
    printf("\n");
}

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

255 0 4 4

Expected Output

15