All submissions

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
    int posvalue= 1 << pos;
    int result= reg & posvalue;
    switch (result) {
    case 0:
        reg |= posvalue;  // was cleared, set it here
        return reg;

    case 1:
    default:
        reg &= (0xFF ^ posvalue);
        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

 

Find the value of the position of the bit,

bitwise AND with register to find it was 0 or 1.

if it was 0, then set it by bitwise OR with posvalue

if it was 1 then bitwise AND with the ones complement of posvalue

 

Loading...

Input

6 1

Expected Output

4