#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", ®, &pos); printf("%d", extractNibble(reg, pos)); return 0; }
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)
Test Cases
Test Results
Input
170 0
Expected Output
10