Extract the Nibble from an 8-bit Register

Code

#include <stdio.h>

unsigned char extractNibble(unsigned char reg, int pos) {
    // Write your code here
    // if(pos == 1) //Since the position here is for nibble and not the actual bit count we have written this if condition. Though this is not a good way to write code, since it makes the code reader confused why we even did this in the first place.
    // {
    //     pos = 4;
    // }
    // int val = (reg>> pos) & 0x0F;

    int bit_position;
    if(pos == 1)
    {
        bit_position = 4;
    }
    else
    {
        bit_position = 0;
    }

    int val = (reg>> bit_position) & 0x0F;
    
    return val;
}

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

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

170 0

Expected Output

10