#include <stdio.h>
unsigned char extractNibble(unsigned char reg, int pos) {
// Write your code here
if (pos == 0){
reg &= (0xFU);
return reg;
}
else{
reg &= (0xFU << 4);
return (reg >> 4);
}
}
int main() {
unsigned char reg;
int pos;
scanf("%hhu %d", ®, &pos);
printf("%d", extractNibble(reg, pos));
return 0;
}
Solving Approach
To check a nibble, 4 Bits- Our mask becomes binary 1111, which is dec 15 or hex 0xF, So we check the bits using the AND operator and then return as is for the lower nibble, or right shift 4 times to return the upper nibble.