Toggle the Bit in an 8-bit Register

Code

#include <stdio.h>
#include <stdint.h>

uint8_t toggle_bit(uint8_t reg, uint8_t pos) {
    // Your code here
    reg ^= (1<<pos);
    return reg;
}

int main() {
    uint8_t reg, pos;
    scanf("%hhu %hhu", &reg, &pos);
    uint8_t result = toggle_bit(reg, pos);
    printf("%u", result);
    return 0;
}

Solving Approach

  1. Think of XOR, it returns 1 only when the two inputs are of different value.

  2. This means that if we XOR a value with 0, the result will be same. i.e 0(reg) ^ 0(mask) = 0 (result), and 1(reg) ^ 0(mask) = 1(result).

  3. So that means we need to left shift 1 to the position we want to bit-toggle, so that, 0(reg) ^ 1(mask) = 1(result), and 1(reg) ^ 1(mask) = 0(result).

  4. This means that Values XOR 0 = Same.

  5. Values XOR 1 = Toggle! 

 

 

Upvote
Downvote
Loading...

Input

6 1

Expected Output

4