Set Multiple Bits in 8-bit Register

Code

#include <stdio.h>

// Function to set bits from start to end
unsigned char setBitsInRange(unsigned char reg, int start, int end) {
    unsigned char mask = ((1 << (end - start + 1)) - 1) << start;
    return reg | mask;
}

int main() {
    unsigned char reg;
    int start, end;

    // Input: register, start, end
    scanf("%hhu %d %d", &reg, &start, &end);

    // Output: updated register
    printf("%d", setBitsInRange(reg, start, end));

    return 0;
}

Solving Approach

Problem Statement

You are given:

  • An 8-bit register value reg (0–255)
  • A start and end position (start, end) with 0 <= start <= end <= 7

Goal:
 Set all bits from position start to end (inclusive) to 1, without changing other bits.

 Solving Approach

  1. Create a bitmask:
    • If start = 1, end = 3, then bits 1, 2, 3 should be set.
    • Formula to create a mask of N bits: (1 << (end - start + 1)) - 1
    • Shift this mask to correct bit position: mask << start
  2. Apply the mask to the register using bitwise OR:
    • reg | (mask << start)

 

Loading...

Input

0 1 3

Expected Output

14