#include <stdio.h>
#include <stdint.h>
uint32_t replace_field(uint32_t reg, uint32_t val, uint8_t pos, uint8_t len) {
// Your code here
// consider inputs are: reg = 0000 0000 0000 0000 0000 0000 1111 1111, val=0000, pos = 4, len = 4
// creating a 32-bit mask and inserting the given value at the given position
uint32_t mask = ( val << pos ); // mask = 0000 0000 0000 0000 1111 1111 0000 0000
// 4
int i;
// make the leading bits as 1 from bit-8 till bit-32 in the mask and make trailing bits as 1 after the
// inserted value=0000.
for ( i = (pos + len); i < 32; i++ )
{
mask = mask | ( 1 << i ); // mask = 1111 1111 1111 1111 1111 1111 0000 0000
// 31 8 4
}
// make trailing bits from bit-1 till bit-4
for ( i = 0; i < pos; i++ )
{
mask = mask | ( 1 << i );// mask = 1111 1111 1111 1111 1111 1111 0000 1111
// 31 8 4 3210
}
// "AND" operation with register and created mask value will give the desired output value
return reg & mask; // reg = 0000 0000 0000 0000 0000 0000 1111 1111
// mask = 1111 1111 1111 1111 1111 1111 0000 1111
// AND operation
// result = 0000 0000 0000 0000 0000 0000 0000 1111
}
int main() {
uint32_t reg, val;
uint8_t pos, len;
scanf("%u %u %hhu %hhu", ®, &val, &pos, &len);
printf("%u", replace_field(reg, val, pos, len));
return 0;
}
Read comments
Input
255 0 4 4
Expected Output
15