Set Multiple Bits in 8-bit Register

Code

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

// uint8_t set_range(uint8_t reg, uint8_t start, uint8_t end) {
//     // Your code here
//     //start will give you the postion to start.
//     //Also here we are setting all the between start and end , so no need to erase anything, can bypass for only this case though.
//     int val = 1;
//     int max = end-start +1;
//     for(int i =1; i<=max; i++)  //there is no function for power that's why I used this.
//     {
//         val *= 2;
//     }
//     val = val -1;
//     //printf ("%d",val);
//     reg = reg | (val << start);
//     return reg;
// }

// uint8_t set_range_2(uint8_t reg, uint8_t start, uint8_t end) {
// // Your code here
// int val =  end - start + 1;
// uint8_t max = 1;

// for (int i = 1 ; i < val ; i++)
// {
//     max |= (max<<1)+1;  //
// }
// reg = reg | (max << start);
// return reg;

//}


//Both the above methods are too complex to achive it.
#include <stdio.h>
#include <stdint.h>

uint8_t set_range_3(uint8_t reg, uint8_t start, uint8_t end) {
    uint8_t mask = ((1U << end+1) - 1) - ((1U << start) - 1);  //simple and succinct
    return reg |= mask;
}


int main() {
    uint8_t reg, start, end;
    scanf("%hhu %hhu %hhu", &reg, &start, &end);
    //printf("%u", set_range(reg, start, end));
    //printf("%u", set_range_2(reg, start, end));
    printf("%u", set_range_3(reg, start, end));
    return 0;
}

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

0 1 3

Expected Output

14