18. Set Multiple Bits in 8-bit Register

Back To All Submissions
Previous Submission
Next Submission

Code

#include <stdio.h>
#include <stdint.h>

void printBinary(uint8_t x);


uint8_t set_range(uint8_t reg, uint8_t start, uint8_t end) {
    // Your code here
    //Get length of zone to set bits
    //printf("Before:\n");
    //printBinary(reg);

    //1. Shift 1 bit to position of how long you wan the length 
    //i.e length between bits is (start-end + 1) 
    //For: Start 1, End 3
    //mask 1 << start-end + 1(0000 1000)
    
    //2. Subtract 1 to make the rest equal 1
    //mask (1 << start-end+1)-1 (0000 0111)

    //3. Shift mask into starting position
    //mask ((1 << start-end+1)-1) << start (0000 1110)
    
    uint8_t mask = ((1 << end-start+1)-1) << start;
    //printf("Mask\n");

    reg |= mask; //OR mask and reg to set the bits
    return reg;
}

int main() {
    uint8_t reg, start, end;
    scanf("%hhu %hhu %hhu", &reg, &start, &end);
    printf("%u", set_range(reg, start, end));
    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