17. Extract the Nibble from an 8-bit Register

Back To All Submissions
Previous Submission
Next Submission

Code

#include <stdio.h>
#include <cstdint>

unsigned char extractNibble(unsigned char reg, int pos) {
    // Write your code here
    //use mask to extract a nibble
    uint8_t mask;

    if (pos == 0) {
        mask = 0x0F;    //lower
        return reg & mask;
    } else {
        mask = 0xF0;     //upper
        return (reg & mask) >> 4;
    }
}

int main() {
    unsigned char reg;
    int pos;
    scanf("%hhu %d", &reg, &pos);
    printf("%d", extractNibble(reg, pos));
    return 0;
}

Solving Approach

 

 

 

Was this helpful?
Upvote
Downvote