Swap individual bits at given position in an integer

Given an integer, swap consecutive b bits starting from given positions in binary representation of the 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 (Number of consecutive bits in each sequence)

Output: 99
(99 in binary is 01100011)

 


 

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
res = 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

 
C++ implementation –
 

Download   Run Code

Output:

15 in binary is 00001111
99 in binary is 01100011

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

 
1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)

Loading...

Thanks for reading.

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 🙂
 



Leave a Reply

avatar
  Subscribe  
Notify of