All submissions

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
    uint8_t set_mask = 0;
    uint8_t clear_mask = 0;
    if(!(start > 7 || end > 7)){
        set_mask = (1 << (end + 1)) - 1; // sets the bits from index 0 to end bit
        clear_mask = ~((1 << (start)) - 1); // sets the bits to 0 from index 0 up to 1 bit before start bit 1
        
        return (reg | (set_mask & clear_mask));
    }
    else {
        return -1;
    }
    
}

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

 

 

 

Loading...

Input

0 1 3

Expected Output

14