Extract a Bit Field from a 32-bit Register

Code

#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", &reg, &pos, &len);
    printf("%u", extract_field(reg, pos, len));
    return 0;
}

Solving Approach

  1. First we need to get rid of all the other bits that are not covered by length (We are not interested in).

  2. reg >> pos, From example 1, reg >>28, leaves us with 0b1011 which are the only bits that we want.

  3. 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.

  4. Finally we and the register with the mask and extract only the bits that we are interested in.

 

 

Upvote
Downvote
Loading...

Input

3060793344 28 4

Expected Output

11