19. Extract a Bit Field from a 32-bit Register

Discussions4
Log in to post comments and replies.
LHongEm
LHongEm
Sep 25 2026

#include <stdio.h>

#include <stdint.h>


 

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

    reg = reg >> pos; // ex 8 bit 1011 0010 --> 0000 1011 : pos 4 , len 3

    reg = reg << (32 - len); // 0110 0000  (8 - 3) <<5

    reg = reg >> (32 - len);// 0000 0110  >>5

    return reg;

}


 

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;

}

0
JAbisek
JAbisek
Sep 16 2026

#include <stdio.h>

#include <stdint.h>


 

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

    // Your code here

    uint32_t res=0;

    reg>>=pos;

    reg<<=(32-len);

    reg>>=(32-len);

    return reg; 

    

}


 

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;

}

0
DevonYates
DevonYates
Jul 29 2026

Yeah I think case 5 is wrong.  I think the answer should be 8

0
78rsingh87
78rsingh87
Jul 26 2026

Case 1 and case 5 both have the same position and length specification. They solution behaves differently. What didn't I understand about the question?

0