#include <stdio.h>
#include <stdint.h>
#define MASK(pos, len) ~(((1U<<len) -1)<<pos)
uint32_t replace_field(uint32_t reg, uint32_t val, uint8_t pos, uint8_t len) {
// Your code here
uint32_t cleared_register = reg & MASK(pos,len);
uint32_t modified_register = cleared_register | (val << pos);
return modified_register;
}
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;
}
/*
Input: reg = 0b1111 1111
val = 0b0000, pos = 4, len = 4
Output: 0b0000 1111
Assume is the len of val is what is len var
Plan:
- create a mask from the position to the length (have all values zeroed out in that range)
- Bitwise AND reg with mask to get the modified reg with the 0 values
- shift the value to the range required
- Bitwise OR the shifted value with the masked register
Mask of len 1s
(1U << len) - 1
example if len = 4
1U<<4 = 0b0001_0000 = 16
16-1 = 0b0000_1111
shift the mask to the correct position
((1U<<len) -1)<<pos
example pos = 4 and len = 4
0b0000_1111 << 4 = 0b1111_0000
Invert the mask to zero out the taget bits
~(((1U<<len) -1)<<pos)
Apply the mask to the register
reg & mask
*/
Input
255 0 4 4
Expected Output
15