#include <stdio.h> #define LOW_NIBBLE 0 #define UPPER_NIBBLE 1 unsigned char extractNibble(unsigned char reg, int pos) { char selected_nibble; switch(pos) { case LOW_NIBBLE: /* Take the four lower nibble (lower bits) 00001111 */ selected_nibble = reg & 0x0F; break; case UPPER_NIBBLE: /* Take the four upper nibble */ reg = (reg >> 4); // Right shift the four upper bits at the low nibble pos. selected_nibble = reg & 0x0F; // Collect the upper nibble. break; default: printf("Invalid nibble pos"); break; } return selected_nibble; } int main() { unsigned char reg; int pos; scanf("%hhu %d", ®, &pos); printf("%d", extractNibble(reg, pos)); return 0; }
Test Cases
Test Results
Input
170 0
Expected Output
10