Set the Bit in an 8-bit Register

durgaramprasadtula
durgaramprasadtula

Code

#include <stdio.h>

// Function to set a specific bit
unsigned char setBit(unsigned char reg, int pos) {
    reg |= (1 << pos);
    return reg;
}

int main() {
    unsigned char reg;
    int pos;

    // Input format: binary number (as decimal) and bit position
    scanf("%hhu %d", &reg, &pos);

    // Output the updated register value
    printf("%d", setBit(reg, pos));

    return 0;
}

Solving Approach
 

  • You're given:
    • An 8-bit register value (reg) as an unsigned char
    • A bit position (pos) to set (0–7, where 0 is the Least Significant Bit)
  • You must set the bit at position pos without changing other bits
  • Use bitwise operations

 

Loading...

Input

5 1

Expected Output

7