# Toggle all the bits of a number except k-th bit.

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.

Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: **DSA Self Paced**. Become industry ready at a student-friendly price.

## Recommended Posts:

- Write an Efficient Method to Check if a Number is Multiple of 3
- Find the Number Occurring Odd Number of Times
- Write an Efficient C Program to Reverse Bits of a Number
- Count set bits in an integer
- Count number of bits to be flipped to convert A to B
- Rotate bits of a number
- Compute modulus division by a power-of-2-number
- Find whether a given number is a power of 4 or not
- Add 1 to a given number
- Next higher number with same number of set bits
- Program to count number of set bits in an (big) array
- Count total set bits in all numbers from 1 to n
- Swap bits in a given number
- Binary representation of a given number
- Swap all odd and even bits
- Check if a number is multiple of 9 using bitwise operators
- How to turn off a particular bit in a number?
- Check if binary representation of a number is palindrome
- Calculate square of a number without using *, / and pow()
- Find nth Magic Number