Replace Bit Field in a 32-bit Register

Code

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

uint32_t replace_register(uint32_t reg, uint32_t new_value, uint8_t pos, uint8_t length){
    uint8_t u8Count = 0; 
    uint8_t end = pos + length - 1; 
    for(uint8_t i = pos; i<=end; i++)
    {   
        reg &= ~(1u<<i); 
    }
    for(uint8_t i=pos; i<=end; i++)
    {
        reg = reg | (((new_value >> u8Count)&0x1) << i);  
        u8Count++; 
    }
    return reg; 
}

int main(){
    uint32_t reg, new_value; 
    uint8_t pos,length; 
    scanf("%u %u %hhu %hhu", &reg, &new_value, &pos, &length); 
    printf("%u",replace_register(reg, new_value, pos, length)); 
    return 0;
}

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

255 0 4 4

Expected Output

15