26. Extract and Modify Field in a 32-bit Register

Back To All Submissions
Previous Submission
Next Submission

Code

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

uint32_t update_register(uint32_t reg) {
    // Your logic here

    int mask = ~0U << 5;
    mask = ~mask;
    mask = mask << 10;
    int value =0;

    // printf ( "%b\n", mask); this showed that the mask was 4 bits between 14 and 11 = 1 I wanted between 14 and 10 for it to be 5 bits of 1 so 
    // from it I made the first stataement push 5 zeros to the lower part 
    // the rest remained same why becasue these 5 zeeos turned 1s and rest zeros (negated), and they became at position 9 ( meaning pushed 10 up) and 
    value =reg & mask;

    value >>=10; // this would have been a bug but slow analysis of steps and walkthrough prevented it the value that we get from above is the correct 5 bits but it is at positoin 9 to 13 which would always be > 31 and not desired we ahd to push these bits down to lowest bits position 0 to 4

    if ( value < 31 ){
        value += 1;
        reg = (reg & ~mask) | (value << 10); //this counters the commented stratement directly before this one to copy the 5 bits on the correct position
    }
    return reg;
}

int main() {
    uint32_t reg;
    scanf("%u", &reg);
    uint32_t updated = update_register(reg);
    printf("%u", updated);
    return 0;
}

Solving Approach

 

 

 

Was this helpful?
Upvote
Downvote