Given a number x and two positions (from right side) in binary representation of x, write a function that swaps n bits at given two positions and returns the result. It is also given that the two sets of bits do not overlap.
Let p1 and p2 be the two given positions.
x = 47 (00101111)
p1 = 1 (Start from second bit from right side)
p2 = 5 (Start from 6th bit from right side)
n = 3 (No of bits to be swapped)
The 3 bits starting from the second bit (from right side) are
swapped with 3 bits starting from 6th position (from right side)
x = 28 (11100)
p1 = 0 (Start from first bit from right side)
p2 = 3 (Start from 4th bit from right side)
n = 2 (No of bits to be swapped)
The 2 bits starting from 0th postion (from right side) are
swapped with 2 bits starting from 4th position (from right side)
We need to swap two sets of bits. XOR can be used in a similar way as it is used to swap 2 numbers. Following is the algorithm.
1) Move all bits of first set to rightmost side set1 = (x >> p1) & ((1U << n) - 1) Here the expression (1U << n) - 1 gives a number that contains last n bits set and other bits as 0. We do & with this expression so that bits other than the last n bits become 0. 2) Move all bits of second set to rightmost side set2 = (x >> p2) & ((1U << n) - 1) 3) XOR the two sets of bits xor = (set1 ^ set2) 4) Put the xor bits back to their original positions. xor = (xor << p1) | (xor << p2) 5) Finally, XOR the xor with original number so that the two sets are swapped. result = x ^ xor
Result = 7
Following is a shorter implementation of the same logic
Swapping individual bits with XOR
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Swap all odd and even bits
- How to swap two bits in a given integer?
- Swap every two bits in bytes
- Check if bits of a number has count of consecutive set bits in increasing order
- Toggle bits of a number except first and last bits
- Number of ways to swap two bit of s1 so that bitwise OR of s1 and s2 changes
- Maximize a given unsigned number number by swapping bits at it's extreme positions.
- Check if a number has same number of set and unset bits
- Set all odd bits of a number
- Same Number Of Set Bits As N
- Set all even bits of a number
- Set all the bits in given range of a number
- Toggle all odd bits of a number
- Toggle all even bits of a number
- Toggle first and last bits of a number
Improved By : vt_m