Bitwise
Toggle Bits
Exclusive-or toggles selected bits while leaving the others alone.
Toggle Bits
toggle_bits.c
#include <stdio.h>
int main(void) {
int flags = ;
int toggled = flags ^ 3;
int restored = toggled ^ 3;
printf("toggled=%d restored=%d\n", toggled, restored);
return 0;
}
#include <stdio.h>
int main(void) {
int flags = ;
int toggled = flags ^ 3;
int restored = toggled ^ 3;
printf("toggled=%d restored=%d\n", toggled, restored);
return 0;
}
#include <stdio.h>
int main(void) {
int flags = ;
int toggled = flags ^ 3;
int restored = toggled ^ 3;
printf("toggled=%d restored=%d\n", toggled, restored);
return 0;
}
xor
`^` flips a bit when the mask has `1` in that position.
repeated toggle
Applying the same toggle twice returns the original bits.