In C programming, toggling a bit is the process of flipping a specific bit of the binary number. It means that the bit that is 0 becomes 1 and a bit that is 1 becomes 0. This operation is useful in the various applications including the cryptography, data compression and hardware control.
In this article, we will learn how to toggle a bit at the given position in a binary number. We will also look at how we can toggle multiple bits as the same time.
How to toggle a bit in C?
Toggling a bit means flipping its value from the 0 to 1 or from the 1 to 0. In C, we can toggle a given bit using the XOR operator (^). Below is the truth table of XOR:

- In 1st operation: 0 ^ 0 resulted in 0.
- In 2nd operation: 0 ^ 1 resulted in 1.
- In 3rd operation: 1 ^ 0 resulted in 1.
- In 4th operation: 1 ^ 1 resulted in 0.
It means that,
By XORing a bit with the 1, the given bit is toggled and by XORing a bit with 0, the given bit is unchanged.
Toggling a Specific Bit in C
To toggle a specific bit in a number, you can use a bit mask with the XOR operator. In that bitmask number, only the bit you want to toggle is set to 1, and all other bits are set to 0.
Example:
Input:
binary_number: 01100111
bit to toggle: 5th
Output:
binary_number: 01100111
mask_used: 00010000
We can use the left shift operator to create mask but remember the 0-based indexing in the shifting.
// C Program to Toogle a given bit of a binary number
#include <stdio.h>
int main()
{
// Binary: 0001 1101
unsigned int num = 29;
// Toggling the 3rd bit (0-based index)
unsigned int bit_position = 2;
// Create a mask with only the 3rd bit set to 1
unsigned int mask = 1 << bit_position;
// Toggle the bit using XOR
num = num ^ mask;
// Print the result
printf("Result: %u\n", num);
return 0;
}
Output
Result: 25
Time Complexity: O(n)
Space Complexity: O(1)
Toggling Multiple Bits in C
We can also toggle multiple bits by creating a mask with multiple bits set to 1. XORing the number with this mask will toggle all corresponding bits.
Example: Toggling the 1st, 3rd, and 4th Bits
// C Program to Toggle multiple bit of a binary number
#include <stdio.h>
int main()
{
// Binary: 0001 1101
unsigned int num = 29;
// Create a mask with the 1st, 3rd, and 4th bits set to
// 1
unsigned int mask = (1 << 0) | (1 << 2) | (1 << 3);
// Toggle the bits using XOR
num = num ^ mask;
// Print the result
printf("Result: %u\n", num);
return 0;
}
Output
Result: 16
Time Complexity: O(n), where n is the number of bits to be flipped.
Space Complexity: O(1)