Given an integer, swap consecutive b bits starting from the given positions in a binary representation of an integer. The bits to be swapped should not overlap with each other.

For example,

Input:
 
n = 15 (15 in binary is 00001111)
p = 2, q = 5 (3rd and 6th bit from the right)
b = 2 (Total number of consecutive bits in each sequence)
 
Output: 99
 
(99 in binary is 01100011)

Practice this problem

The idea is to store the result of XORing the pairs of bit values we want to swap in a variable x, and then the bits are set to the result of themselves XORed with x. The code goes as:

// isolate the bits to be swapped and take their XOR
x = ((n >> p) ^ (n >> q)) & ((1 << b) – 1)
 
// replace the bits to be swapped with the XOR bits and take its XOR with n
result = n ^ ((x << p) | (x << q))

Note that the result is undefined if the sequences overlap.

 
For example, consider n = 15, p = 2, q = 5 (3rd and 6th bit from the right) and number of consecutive bits in each sequence b = 2.

00001111                (n = 15)
 
00000011    ^           (n >> p)
00000000                (n >> q)
~~~~~~~~
00000011                ((n >> p) ^ (n >> q))
 
 
00000011    &           ((n >> p) ^ (n >> q))
00000011                ((1 << b) – 1)
~~~~~~~~
00000011                x
 
 
00001100    |           (x << p)
01100000                (x << q)
~~~~~~~~
01101100                ((x << p) | (x << q))
 
 
00001111    ^           (n = 15)
01101100                (n ^ ((x << p) | (x << q)))
~~~~~~~~
01100011

Following is the C++, Java, and Python implementation of the idea:

C++


Download  Run Code

Output:

15 in binary is 00001111
99 in binary is 01100011

Java


Download  Run Code

Output:

15 in binary is 00001111
99 in binary is 01100011

Python


Download  Run Code

Output:

15 in binary is 0b1111
99 in binary is 0b1100011

References: https://graphics.stanford.edu/~seander/bithacks.html#SwappingBitsXOR