In binary, toggling a bit can be done using the XOR (^) operator.
The 5th bit (0-based index) is represented by 1 << 5, which equals 32 (decimal).
N ^ 32 flips only the 5th bit of N.
Code Implementation:
#include <stdio.h>
int toggleFifthBit(int n) {
return n ^ (1 << 5); // Toggle the 5th bit using XOR
}
int main() {
int n;
scanf("%d", &n);
printf("%d", toggleFifthBit(n));
return 0;
}
Explanation:
If the 5th bit is 0, XOR with 32 will set it to 1.
If the 5th bit is 1, XOR with 32 will reset it to 0.