Set Multiple Bits in 8-bit Register

Code

#include <stdio.h>
#include <stdint.h>
/*
 * Function: set_bits_range
 * -----------------------
 * Sets all bits in an 8-bit register between positions
 * 'start' and 'end' (inclusive), using 0-based indexing.
 *
 * reg   : original 8-bit register value
 * start : starting bit position
 * end   : ending bit position (start <= end)
 *
 * returns: updated register with specified bits set
 */
uint8_t set_range(uint8_t reg, uint8_t start, uint8_t end) {
    // Create a mask with (end - start + 1) consecutive 1s
    // Example: start=2, end=5 → (1 << 4) - 1 = 00001111
    uint8_t mask = (1 << (end - start + 1)) - 1;

    // Shift the mask left so the 1s align with bits start to end
    // Example: 00001111 << 2 = 00111100
    mask <<= start;

    // Use bitwise OR to set the specified bits in the register
    // Existing bits outside the range remain unchanged
    return reg | mask;
}

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

 

 

 

Upvote
Downvote
Loading...

Input

0 1 3

Expected Output

14