All submissions

Set or Clear a Specific Bit in a Register

Code

#include <stdio.h>

unsigned char modifyBit(unsigned char reg, int pos, int mode) {
    // Write your code here
     if (mode == 1) {
        // Set the bit at 'pos'
        reg |= (1 << pos);
    } else if (mode == 0) {
        // Clear the bit at 'pos'
        reg &= ~(1 << pos);
    }
    return reg;
}

int main() {
    unsigned char reg;
    int pos, mode;
    scanf("%hhu %d %d", &reg, &pos, &mode);
    printf("%d", modifyBit(reg, pos, mode));
    return 0;
}

Solving Approach

1. Understand Bitwise Operations

To set or clear a bit, use bitwise operations:

  • Set bit at position pos: reg | (1 << pos)
  • Clear bit at position pos: reg & ~(1 << pos)

2. Function Logic

Create a function:

"unsigned char modifyBit(unsigned char reg, int pos, int mode)"

  • Use if statement:
    • If mode == 1, set the bit using reg |= (1 << pos)
    • If mode == 0, clear the bit using reg &= ~(1 << pos)
  • Return modified register.

3. Main Function Steps

  • Read inputs: register (reg), bit position (pos), and mode (mode) using scanf.
  • Call modifyBit with inputs.
  • Print the result.

4. Why It Works

  • The register is 8-bit: unsigned char ensures it's within 0–255.
  • Bit positions are 0–7 → valid for 8 bits.
  • Bitwise operations directly manipulate the desired bit.

 

 

Loading...

Input

10 3 1

Expected Output

10