Given a positive (or unsigned) integer **n**, write a function to toggle all the bits except k-th bit. Here value of k starts from 0 (zero) and from right.

Examples:

Input : n = 4294967295, k = 0 Output : 1 The number 4294967295 in 32 bits has all bits set. When we toggle all bits except last bit, we get 1. Input : n = 1, k = 1 Output : 4294967292 4294967262 has all bits toggled except second bit from right.

- Toggle bit at k-th position. We do it by finding a number with only k-th bit set (using 1 << k), then doing bitwise XOR of this number n.
- Toggle all bits of number obtained above using ~ (Bitwise negation)

`// C program to toggle all bits except kth bit ` `#include<stdio.h> ` ` ` `// Returns a number with all bit toggled in n ` `// except k-th bit ` `unsigned ` `int` `toggleAllExceptK(unsigned ` `int` `n, ` ` ` `unsigned ` `int` `k) ` `{ ` ` ` `/* 1) Toggle k-th bit by doing n ^ (1 << k) ` ` ` `2) Toggle all bits of the modified number */` ` ` `return` `~(n ^ (1 << k)); ` `} ` ` ` `// Driver code ` `int` `main() ` `{ ` ` ` `unsigned ` `int` `n = 4294967295; ` ` ` `unsigned ` `int` `k = 0; ` ` ` `printf` `(` `"%u"` `, toggleAllExceptK( n, k)); ` ` ` `return` `0; ` `} ` |

*chevron_right*

*filter_none*

Output:

1

This article is contributed by **Mandula Vikitha**. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the **DSA Self Paced Course** at a student-friendly price and become industry ready.

## Recommended Posts:

- Toggle bits of a number except first and last bits
- Toggle all bits after most significant bit
- For every set bit of a number toggle bits of other
- Toggle all even bits of a number
- Toggle all odd bits of a number
- Program to toggle K-th bit of a number N
- Set, Clear and Toggle a given bit of a number in C
- Toggle first and last bits of a number
- Minimum bit flips such that every K consecutive bits contain at least one set bit
- Toggle the last m bits
- Toggle bits in the given range
- Number formed by flipping all bits to the left of rightmost set bit
- Queries for number of array elements in a range with Kth Bit Set
- Smallest number exceeding N whose Kth bit is set
- Check if all bits can be made same by flipping two consecutive bits
- Construct an array from XOR of all elements of array except element at same index
- Unique element in an array where all elements occur k times except one
- Invert the Kth most significant bit of N
- Check if bits of a number has count of consecutive set bits in increasing order
- Inserting m into n such that m starts at bit j and ends at bit i.