# Swap two bits at given position in an integer

Given an integer, swap two bits at given positions in binary representation of it.

For example,

Input:
n = 31 (31 in binary is 00011111)
p = 2, q = 6 (3rd and 7th bit from the right)

Output: 91

Explanation: 91 in binary is 01011011

We can solve this problem by checking if the two bits at given positions are same or not. If they are same, nothing needs to be done else if they are not the same (i.e one is 0 and other is 1), then we can simply XOR them with (1 << pos) where pos is given positions. This will work because

XOR with 1 will toggle the bits
0 ^ 1 = 1
1 ^ 1 = 0

XOR with 0 will have no impact
0 ^ 0 = 0
1 ^ 0 = 1

## C++

Output:

31 in binary is 00011111
91 in binary is 01011011

## Java

Output:

31 in binary is 00011111
91 in binary is 01011011

As pointed out by reader in comments below, we could hoist (1 << p) and (1 << q) into a variable to avoid doing repeated work. We can also remove the conditional check and do the swap in any case to avoid unnecessary memory reads as shown below –     (1 votes, average: 5.00 out of 5) Loading...

Please use our online compiler to post code in comments. To contribute, get in touch with us.
Like us? Please spread the word and help us grow. Happy coding 🙂 Subscribe
Notify of Guest

Minor improvement suggestions:

You could hoist (1 << p) and (1 << q) into a variable to not have to do it twice. Would also help with readability.

Even better you can actually remove the check and do the swap in any case. The check just results in unnecessary memory reads. Guest

You cannot remove the check because swapping in any case is incorrect. Try swap(3, 0, 1) or swap(0, 0, 1). Guest
Sameer Mahant

Check output of your program for `p = 2` and`q = 4`.
I think in swap() function p and q should be:
```p = 8 - p; q = 8 - q;``` Guest
Swapnil Dongre

Please can you try the above program without check(as you mentioned it will work for all the cases) for below inputs.

int n = 47,
int p = 1;
int q = 5;

We should get output as 47.