All submissions

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
    int mask = 0;
    for(int i=0;i<len;i++)
        mask = mask | (1<<i);
    return reg>>pos & mask;
}

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

Considering Example 1

Input: reg = 0b1011 0110 0111 0000 0000 0000 0000 0000, pos = 28, len = 4 
Output: 0b1011 
   
     for(int i=0;i<len;i++){
        mask = mask | (1<<i);
    }

#include <stdio.h>

#include <stdint.h>


 

uint32_t extract_field(uint32_t reg, uint8_t pos, uint8_t len) {

    // Your code here

    int mask = 0;

    for(int i=0;i<len;i++)

        mask = mask | (1<<i);

    return reg>>pos & mask;

}

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;

}

 

here mask is --> 0000 0000 0000 0000 0000 0000 0000 1111

return reg >> pos & mask;

reg >> pos  -->  0000 0000 0000 0000 0000 0000 0000 1011

 

mask          -->   0000 0000 0000 0000 0000 0000 0000 1111

reg >> pos  -->  0000 0000 0000 0000 0000 0000 0000 1011

                        & --------------------------------------------------------------------------

  result     -->       0000 0000 0000 0000 0000 0000 0000 1011

                          ------------------------------------------------------------------------------

 

 

Loading...

Input

3060793344 28 4

Expected Output

11