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 temp=0;
    // for( char a =10 ; a<=14 ; a++){
    //     if( reg & ( 1<<a)){
    //         temp |= (1<<(a-10));
    //     }
    // }
    // extract field by mask
    temp = ( reg >> 10) & 0x1F;
    if( temp <31) {
        temp +=1;
    }
    // clear old field and update new field there ( bit 10 to 14) 
    // for( char a =10 ; a<=14 ; a++){
    //     if( temp & ( 1<<(a-10))){
    //         reg |= (1<<a);
    //     }
    //     else {
    //         reg &= ~(1<<a);
    //     }
    // }

//clear all 5 bits by using a mask 
    reg &= ~(0x1F << 10);
    // use mask to update all 5 bits at once
    reg |= (temp<<10);
    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