#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
int mask = 0;
for(int i=0;i<len;i++){
mask = mask | (1<<i);
}
reg = reg & ~(mask << pos);
return reg = reg | (val & mask) << pos;
}
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;
}
#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
int mask = 0;
for(int i=0;i<len;i++){
mask = mask | (1<<i);
}
reg = reg & ~(mask << pos);
return reg = reg | (val & mask) << pos;
}
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;
}
#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
int mask = 0;
for(int i=0;i<len;i++){
mask = mask | (1<<i);
}
reg = reg & ~(mask << pos);
return reg = reg | (val & mask) << pos;
}
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;
}
for(int i=0;i<len;i++){
mask = mask | (1<<i);
}
1.after completion of for loop mask is
mask = 1111
2.reg = reg & ~(mask << pos);
reg = 1111 1111
(mask << pos) = 1111 0000
~(mask << pos) = 0000 1111
now we are doing '&' and operation between this reg & ~(mask << pos)
reg -> 1111 1111
~(mask << pos) -> 0000 1111
result -> & 0000 1111
reg = result
we are storing result in reg.
3.
reg = reg | (val & mask) << pos
val -> 0000 0000
mask -> 0000 1111
(val & mask) = 0000 0000
now i am left shifting (val & mask) provided position
( (val & mask) << pos ) = 0000 0000
4.
reg value is -> 0000 1111
(val & mask) << pos value is -> 0000 0000
or '|' operation between reg | (val & mask) << pos
reg -> 0000 1111
(val & mask) << pos -> 0000 0000
output -> (or) 0000 1111
this is the final output --> 0000 1111
Input
255 0 4 4
Expected Output
15