Extract the Nibble from an 8-bit Register

Code

#include <stdio.h>

unsigned char extractNibble(unsigned char reg, int pos) {
    if ( pos == 0)
       return reg & 0x0F;
    else
       return (reg >> 4) & 0x0F; 
}

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

Solving Approach

  • If pos = 0 (lower nibble): mask lower 4 bits → reg & 0x0F.
  • If pos = 1 (upper nibble): shift 4 bits right → (reg >> 4), then mask lower 4 bits → & 0x0F.
  • Return the extracted nibble.

 

 

Upvote
Downvote
Loading...

Input

170 0

Expected Output

10