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)
        reg|=(1U<<pos);
    
    else
        reg &= ~(1U<<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. Create a Mask: A mask is generated to isolate the target bit at position pos. This is done by shifting the number 1 to the left by pos places (1U << pos). The result is a number with a 1 only at the target bit position and 0s everywhere else.

  2. Check the Mode:

    • To Set the Bit (mode 1): The code uses the bitwise OR operator (|). The original number is OR'd with the mask. This forces the target bit to become 1 (x | 1 = 1) while leaving all other bits unchanged (x | 0 = x).
    • To Clear the Bit (mode 0): The code uses the bitwise AND (&) operator with an inverted mask (~). Inverting the mask creates a number with a 0 only at the target position. AND'ing with this forces the target bit to 0 (x & 0 = 0) while preserving all other bits (x & 1 = x).


 

 

 

Upvote
Downvote
Loading...

Input

10 3 1

Expected Output

10