Set or Clear a Specific Bit in a Register

Code

#include <stdio.h>

int main() {
    unsigned char reg;
    int pos, op;
    scanf("%hhu %d %d", &reg, &pos, &op);
    
    if (op == 1) {
        reg |= (1 << pos);
    } else {
        reg &= ~(1 << pos);
    }
    
    printf("%d", reg);
    return 0;
}

Solving Approach

Use bitwise operators to modify specific bits while preserving others


Set Bit (1): Use OR with a bitmask (1<<pos )to force that bit to 1

Clear Bit (0): Use AND with inverted mask ~(1<<pos) to force that bit to 0

(1<<pos) creates a number with only the target bit set

 

 

Upvote
Downvote
Loading...

Input

10 3 1

Expected Output

10