#include <stdio.h> #include <stdint.h> uint32_t extract_field(uint32_t reg, uint8_t pos, uint8_t len) { // Your code here return((reg >> pos) & ((1<<len)-1)); } int main() { uint32_t reg; uint8_t pos, len; scanf("%u %hhu %hhu", ®, &pos, &len); printf("%u", extract_field(reg, pos, len)); return 0; }
First we need to get rid of all the other bits that are not covered by length (We are not interested in).
reg >> pos, From example 1, reg >>28, leaves us with 0b1011 which are the only bits that we want.
Now we need to create a mask for the 4 bits, to create a mask we left shift then minus 1, e.g 1<<4 = 0b10000, then 0b10000 - 1U = 0b1111.
Finally we and the register with the mask and extract only the bits that we are interested in.
Test Cases
Test Results
Input
3060793344 28 4
Expected Output
11