VOOZH about

URL: https://www.geeksforgeeks.org/c/toggling-bits-in-c/

⇱ Toggling bits in C - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Toggling bits in C

Last Updated : 10 Jul, 2024

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:

👁 Truth-table-for-XOR-operation
  • 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.


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


Output
Result: 16

Time Complexity: O(n), where n is the number of bits to be flipped.
Space Complexity: O(1)

Comment
Article Tags: