![]() |
VOOZH | about |
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.
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:
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.
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.
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.
Result: 25
Time Complexity: O(n)
Space Complexity: O(1)
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.
Result: 16
Time Complexity: O(n), where n is the number of bits to be flipped.
Space Complexity: O(1)