Clear the Bit in an 8-bit Register

durgaramprasadtula
durgaramprasadtula

Code

#include <stdio.h>

// Function to clear a specific bit
unsigned char clearBit(unsigned char reg, int pos) {
    reg &= ~(1 << pos);  // Clear the bit at position 'pos'
    return reg;
}

int main() {
    unsigned char reg;
    int pos;

    // Input register value and bit position
    scanf("%hhu %d", &reg, &pos);

    // Output the modified register
    printf("%d", clearBit(reg, pos));

    return 0;
}

Solving Approach

Step 1: Understand Bit Clearing

To clear a specific bit, you need to:

  1. Create a mask that has 0 at the desired position and 1 elsewhere.
  2. Use the bitwise AND (&) operator with that mask.

Step 2: Construct the Bit Mask

Use:

1 << pos

This shifts a 1 to the desired bit position.

Use:

~(1 << pos)

To invert it — gives a mask with 0 at that position and 1s elsewhere.

Step 3: Apply Bitwise AND

reg = reg & ~(1 << pos);

This operation clears the bit at pos.

 

 

Loading...

Input

7 0

Expected Output

6