Extract the Nibble from an 8-bit Register

Code

#include <stdio.h>

unsigned char extractNibble(unsigned char reg, int pos) {
    // If pos is 1, shift the upper nibble to the lower position
    if (pos == 1) {
        reg = reg >> 4;
    }
    
    // Mask with 0x0F (0000 1111) to isolate the 4 bits
    return reg & 0x0F;
}

int main() {
    unsigned char reg;
    int pos;
    
    // Note: %hhu is used for unsigned char (8-bit)
    if (scanf("%hhu %d", &reg, &pos) == 2) {
        printf("%d", extractNibble(reg, pos));
    }
    
    return 0;
}

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

170 0

Expected Output

10