Extract the Nibble from an 8-bit Register

Code

#include <stdio.h>

unsigned char extractNibble(unsigned char reg, int pos) {
    // Write your code here
    unsigned int reg1 = 0,ans = 0;
    reg1 |= (reg << 0);
    if(pos == 0){
        ans |= (reg1 &  (0xf << 0));
    }
    else{
        ans |= ((reg1 & (0xf << 4)) >> 4);
    }
    return ans;
}

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

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

170 0

Expected Output

10