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 |= (1 << pos);  // Set bit n
    }else if (mode == 0) {
        reg &= ~(1 << pos);  // Clear bit n
    }
    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

 01010

We want to Set (turn ON) the switch at Index 3. Notice that the switch at Index 3 is already 1 (ON). Let's see how the code handles this.

Step 1: Making the "Pointer" (1 << 3)

To target a specific switch without touching the others, we need a Mask that points only to index 3.

  • We take 1 (00000001) and shift it left by 3 positions.
  • This gives us our Mask: 00001000 (which is 8 in decimal).

Step 2: The "Set" Command (|)

Because your mode is 1, your code runs this line: reg |= (1 << pos);. The | symbol represents Bitwise OR. Think of OR as a forceful "ON" button:

  • If the Mask has a 0, OR says: "Leave this switch alone."
  • If the Mask has a 1, OR says: "Force this switch ON!"

Step 3: Seeing it in Action

Let's stack our original register and our mask on top of each other and apply the OR rules:

Index:      7 6 5 4 3 2 1 0
---------------------------
Original:   0 0 0 0 1 0 1 0   (This is 10)
Mask:     | 0 0 0 0 1 0 0 0   (This is 1 << 3)
---------------------------
Result:     0 0 0 0 1 0 1 0   (This is 10)

Look at what happened: At Index 3, the Mask had a 1, forcing the switch ON. Because the original switch was already ON (1 | 1 = 1), it just stays ON. Everywhere else, the Mask had a 0, so the original switches stayed exactly the same.

Final Output: The register value remains 10.

What if the mode was 0 (Clear)?

If your input was 10 3 0 instead, the code would run reg &= ~(1 << pos); to turn that switch OFF. It would invert the mask to 11110111 and use AND (&) as a strict filter:

Index:      7 6 5 4 3 2 1 0
---------------------------
Original:   0 0 0 0 1 0 1 0   (This is 10)
Mask:     & 1 1 1 1 0 1 1 1   (This is ~(1 << 3))
---------------------------
Result:     0 0 0 0 0 0 1 0   (This is 2)

 

 

Upvote
Downvote
Loading...

Input

10 3 1

Expected Output

10