Extract and Modify Field in a 32-bit Register

Code

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

uint32_t update_register(uint32_t reg) {
    // Your logic here
    uint32_t mask = (((1U << 5) - 1U) << 10);
    mask = ((reg & mask) >> 10);
    if(mask < 31){
        uint8_t m = 1;
        //Checking if current bit is 1, if so flip that bit 
        //and then move to the next bit until we find first 0 bit(from LSB)
        while (mask & m){
            mask ^= m;
            m <<= 1;
        }

        //flip that first 0 bit to 1
        //(all trailing 1's have already been flipped to 0 in loop)
        mask ^= m; 
        reg &= (~(((1U << 5) - 1U) << 10));    //Resetting the bits 10 to 14
        reg |= (mask << 10);                   //Setting as per new incremented value
    }
    
    return reg;
}

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

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

15360

Expected Output

16384