#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", ®, &pos);
uint8_t result = toggle_bit(reg, pos);
printf("%u", result);
return 0;
}
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
Input
6 1
Expected Output
4