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

The solution relies on two essential bitwise operators in C:

  1. Bitwise OR (|): Used to set a bit. The result of A | B is 1 if at least one of the bits in the corresponding position of A or B is 1.
    • X | 0 is X
    • X | 1 is 1 (this is the key to setting the bit)
  2. Bitwise AND (&): Used to clear a bit. The result of A & B is 1 only if both bits are 1.
    • X & 1 is X
    • X & 0 is 0 (this is the key to clearing the bit)
  3. Left Shift (<<): Used to create a mask (a number with a single '1' at the desired position). 1 << N creates a value where only the Nth bit is '1'.
  4. Bitwise NOT (~): Used to invert a mask for clearing a bit. ~Mask turns the '1' in the mask into a '0', and all the '0's into '1's.

Logic for Setting a Bit

To set a specific bit at position pos, we need a mask where only that bit is 1, and then we use the | operator with the register value.

Steps:

  1. Create a mask: Use 1 << pos. This puts a 1 at the desired bit position and 0 everywhere else.
    • Example (pos = 3): 1 << 3 results in 00001000.
  2. Apply the mask: Use the bitwise OR operator (|) between the register and the mask. The 0s in the mask leave the other bits of the register unchanged, while the 1 in the mask forces that specific bit to become 1.
    • Code: register_value = register_value | (1 << pos);

Logic for Clearing a Bit

To clear a specific bit at position pos, we need a mask where only that bit is 0, and then we use the & operator with the register value.

Steps:

  1. Create a mask with a '1' at the position: Use 1 << pos.
    • Example (pos = 3): 1 << 3 results in 00001000.
  2. Invert the mask: Use the bitwise NOT operator (~) to flip all the bits. The 1 becomes 0, and all other 0s become 1s.
    • Example (pos = 3): ~(00001000) results in 11110111.
  3. Apply the inverted mask: Use the bitwise AND operator (&) between the register and the inverted mask. The 1s in the mask leave the other bits of the register unchanged, while the 0 in the mask forces that specific bit to become 0.
    • Code: register_value = register_value & (~(1 << pos));

 

 

 

 

 

 

 

 


 

 

 

Upvote
Downvote
Loading...

Input

10 3 1

Expected Output

10