18. Set Multiple Bits in 8-bit Register

Back To All Submissions
Previous Submission
Next Submission

Code

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

uint8_t set_range(uint8_t reg, uint8_t start, uint8_t end) {
    // Your code here
    if((start<8) && (start>=0))
    {
        if((end<8) && (end>=start))
        {
            // for(uint8_t i = start;i<=end;i++)
            // {
            //     reg |= 1<<i;
            // }
            // uint8_t len = end - start+1;
            return reg |= ((1<<(end - start+1))-1)<<start;
        }
        else
        {
            return 0;
        }
    }
    else
    {
        return 0;
    }
    return 0;
}

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

Solving Approach

 

 

 

Was this helpful?
Upvote
Downvote