#include <stdio.h>
unsigned char extractNibble(unsigned char reg, int pos) {
// Write your code here
if(pos == 1)
{
reg = ((reg >> 4) & (0x0F));
}
else
{
reg = (reg & 0x0F);
}
return reg;
}
int main() {
unsigned char reg;
int pos;
scanf("%hhu %d", ®, &pos);
printf("%d", extractNibble(reg, pos));
return 0;
}
Based on the position of nibble (upper or lower), a bit shif operation is performed. If the upper nibble is preffered, a right shift operation by 4 bits is done and then an and operation with (0x0F) to return the upper nibble value. In case of lower nibble, a simple AND operation with 0x0F will return the lower nibble.
Input
170 0
Expected Output
10