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 < 0) | (end > 7) | (start > end))
        return 0;
    uint8_t bit_num = end - start + 1;      // cal number of bits 1
    uint8_t mask = (1U << bit_num) - 1U;    // create a mask with 
                                            // valid number of bits 1 

    reg = reg | (mask << start);            // shift bits 1 to right position then AND
    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;
}

Solving Approach

 

 

 

Was this helpful?
Upvote
Downvote