Extract the Nibble from an 8-bit Register

hetmhs007
hetmhs007

Mast Code

#include <stdio.h>

unsigned char extractNibble(unsigned char reg, int pos) {
    return (pos? (reg = (reg &= 240) >> 4) : (reg &= 15));

    // below is simplification 
    // if(pos == 0){
    //     reg &= 15;
    //     return reg;
    // }
    // else if(pos == 1){
    //     reg &= 240;
    //     reg = reg >> 4;
    //     return reg;
    // }
}

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

Solving Approach

Simple first check for higher nibble or lower nibble accordingly do and operation to make the other nibble data 0 and right shift for higher nibble to get correct data,

done 

and for single line approach (thanks Yash bhai)

 

 

Loading...

Input

170 0

Expected Output

10