17. Extract the Nibble from an 8-bit Register

Back To All Submissions
Previous Submission
Next Submission

Code

#include <stdio.h>
#include <stdint.h>
void printBinary(uint8_t x);

unsigned char extractNibble(unsigned char reg, int pos) {
    // Write your code here
    //To extract a 4 bit nible, we need a mask of 1111 to and with register
    //then shift mask 0 or 4 places to left
    //i.e reg 1010    1110
    //mask    1111 or 1111
    if (pos == 0){
        reg &= reg & 0x0F;
        //printf("Pos 0\n");
        //printBinary(reg);
    }
    else{
        reg &= (reg >> 4) & 0x0F;
        //printf("Pos 1\n");
        //printBinary(reg);
    }
    return reg;
}

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


//FUNCTION TO PRINT BINARY 8 bit
void printBinary(uint8_t x){
    //1. Find size of passed int
    int num_bits = sizeof(x)*8;
    //2. loop through every bit and perform checkbit
    //printf("Int value is: %hhu, Num of bits is: %d\n",x, num_bits);
    for(int i=num_bits-1;i>=0;i--){
    //Prints a space every 4 bits
    if ((i+1)%4==0 && i+1 != sizeof(x)*8){
        printf(" ");
    }
    if (x & (1 << i)){
        printf("1");
    } 
    else{
        printf("0");
    }
    }
    printf("\n");
}

Solving Approach

 

 

 

Was this helpful?
Upvote
Downvote