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++

Download   Run Code

Output:

31 in binary is 00011111
91 in binary is 01011011

Java

Download   Run Code

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 –

 

 
Thanks for reading.




Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
Sort by:   newest | oldest | most voted
Sameer Mahant
Sameer Mahant

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

didito
didito

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.

wpDiscuz