Extract Bit Field from 16-bit Register

Code

#include <stdio.h>
#include <stdint.h>

uint8_t extract_field(uint16_t reg) {
    // 1. Shift right by 4 to bring bit 4 to the LSB position
    // 2. Mask with 0x1F (binary 0001 1111) to isolate the 5 bits
    return (reg >> 4) & 0x1F;
}

int main() {
    uint16_t reg;
    if (scanf("%hx", &reg) == 1) {
        printf("%u", extract_field(reg));
    }
    return 0;
}

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

0x01F0

Expected Output

31