All submissions

Set or Clear a Specific Bit in a Register

Code

#include <stdio.h>

// Function to modify a specific bit
unsigned char modifyBit(unsigned char reg, int pos, int mode) {
    if (mode == 1) {
        
        reg |= (1 << pos);             // Set the bit at position 'pos'
    } else {
       
        reg &= ~(1 << pos);           // Clear the bit at position 'pos'
    }
    return reg;
}

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

   
    scanf("%hhu %d %d", &reg, &pos, &mode);       // Input: register value, bit position, and mode (0 or 1)

  
    printf("%d", modifyBit(reg, pos, mode));     // Output: modified register value

    return 0;
}

Solving Approach

  • (1 << pos) → creates mask
  • |= → sets that bit
  • &= ~() → clears that bit
  • mode (1 or 0) decides which operation to do

 

 

 

 

Loading...

Input

10 3 1

Expected Output

10