Set Multiple Bits in 8-bit Register

Code

#include <stdio.h>
#include <stdint.h>
uint8_t setBitRange(uint8_t reg, int start, int end) {
    uint8_t mask = 0;

    // Build mask with bits start..end set to 1
    for (int i = start; i <= end; i++) {
        mask |= (1u << i);
    }

    // Set bits in the register
    reg |= mask;

    return reg;
}

int main() {
    uint8_t reg;
    int start, end;

    scanf("%hhu %d %d", &reg, &start, &end);

    printf("%hhu", setBitRange(reg, start, end));

    return 0;
}

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

0 1 3

Expected Output

14