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 == 0) {
        return reg &= ~(1 << pos);
    }

    else {
        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

In C, bitwise operations allow direct manipulation of individual bits within a byte, word, or register. These operations are performed using the following operators:

  • | → Bitwise OR — typically used to set a bit
  • & → Bitwise AND — used to clear or check a bit
  • ^ → Bitwise XOR — used to toggle (invert) a bit
  • ~ → Bitwise NOT — used to flip all bits (1 to 0, 0 to 1)
  • << >> → Bit shift left/right — used to move bit positions
     

Common bit-masking patterns:

reg |= (1 << n);     // Set bit n
reg &= ~(1 << n);    // Clear bit n
reg ^= (1 << n);     // Toggle bit n
if (reg & (1 << n))  // Check if bit n is set

These operations are used to target and modify only specific bits, without disturbing others.

 

 

Upvote
Downvote
Loading...

Input

10 3 1

Expected Output

10