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) {
    return ((((1U << (end - start + 1)) - 1) << start) | reg);
}

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

/*
    00000000 -> 00001110

    0xFF = 11111111 >> 5 = 00000111 << 1 = 00001110

    0xFF = 11111111 >> 6 = 00000011 << 0 = 00000011 | 00001000 = 00001011

    1U = (00000001 << (end - start + 1) - 1) << start

    00000001 << 3 = 00001000 - 1 = 00000111 << 1 = 00001110
*/

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

0 1 3

Expected Output

14