Toggle the Bit in an 8-bit Register

durgaramprasadtula
durgaramprasadtula

Code

#include <stdio.h>

// Function to toggle a specific bit
unsigned char toggleBit(unsigned char reg, int pos) {
    reg ^= (1 << pos);  // Toggle bit at position 'pos'
    return reg;
}

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

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

    // Output: modified register value
    printf("%d", toggleBit(reg, pos));

    return 0;
}

Solving Approach

Step 1: Understand Bit Toggling

To toggle a bit:

  • Use the bitwise XOR operator ^
  • XOR with 1 flips the bit:
    • 1 ^ 1 = 0
    • 0 ^ 1 = 1

Step 2: Create Bit Mask

Use:

1 << pos

This shifts a 1 into the bit position you want to toggle.

Step 3: Apply XOR

reg = reg ^ (1 << pos);

 

 

Loading...

Input

6 1

Expected Output

4