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) {
    if (mode == 1) {
        // Set the bit at position 'pos'
        return reg | (1 << pos);
    } else {
        // Clear the bit at position 'pos'
        return reg & ~(1 << pos);
    }
}



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

An 8-bit register holds values from 0 to 255, represented in binary as 00000000 to 11111111. Each bit position (0 to 7) can be individually manipulated using bitwise operations.

🛠️ Step-by-Step Solving Approach

  1. Input Handling
    • Read three values from the user:
      • reg: the 8-bit register value (unsigned char)
      • pos: the bit position to modify (0–7)
      • mode: operation mode (1 to set, 0 to clear)
  2. Validation (Optional but recommended)
    • Ensure pos is between 0 and 7
    • Ensure mode is either 0 or 1
  3. Bit Manipulation Logic
    • Use bitwise operators to modify the bit:
      • Set a bit: reg | (1 << pos)
        • Shifts 1 left by pos bits to create a mask
        • ORs the mask with reg to set the bit
      • Clear a bit: reg & ~(1 << pos)
        • Shifts 1 left by pos bits to create a mask
        • Inverts the mask with ~ to get all 1s except the target bit
        • ANDs the inverted mask with reg to clear the bit
  4. Return or Print the Result
    • Output the modified register value in decimal

🔍 Example Walkthrough

Input: reg = 10, pos = 3, mode = 1

  • Binary of 10: 00001010
  • 1 << 300001000
  • reg | 0000100000001010 → Decimal 10 (bit already set)

Input: reg = 10, pos = 1, mode = 0

  • Binary of 10: 00001010
  • 1 << 100000010
  • ~0000001011111101
  • reg & 1111110100001000 → Decimal 8

 

 

Loading...

Input

10 3 1

Expected Output

10