Extract the Nibble from an 8-bit Register

RodrigoGruntmanis
RodrigoGruntmanis

Solving Approach

How do you plan to solve it?

Something similar like the first task, using operands. I will make a mask, its like telling...this is the part that interests me. So for the first one i was interested in the second half of the byte. So i use 0xF0 in binary 11110000. Then using and operand, it checks where are matching 1 and that's it.

The number 170

10101010 <-number

11110000 <-mask

==========

10100000 <-result

And to get it so its a 4 bit number, i need to shift it 4 spaces to the right.

reg = reg >> 4;

Code

#include <stdio.h>

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

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

 

Loading...

Input

170 0

Expected Output

10