Example: Swap bits - rFronteddu/general_wiki GitHub Wiki
Given an integer x, swap n bits starting at position p1 with n bits starting at position p2 and return the resulting integer.
// extract the n bits starting at position p1, first we shift the bits to the right
// apply a mask for the rightmost n bits set to 1
int set1 = (x >> p1) & ((1 << n) - 1);
// extract the n bits starting at position p2
int set2 = (x >> p2) & ((1 << n) - 1);
// get the bits that are different to swap the values between the two sets
int xor = (set1 ^ set2);
// position the xored bits back to their original positions
xor = (xor << p1) | (xor << p2);
// swap the bits in the original number (swaps the bits between p1 and p2)
int result = x ^ xor;
return result;
Example
- Consider 47 (101111) p1=1 p2=5 n=3
- 101111 >> 1 = 010111
- Mask ((1<<3) - 1) = 000111
- set1 = 010111 & 000111 = 011
Similarly for set 2 we get:
- set2 = 000001 & 000111 = 001
xor = set1 ^ set2 = 011^001=010, these are the bits that differ between set1 and set2
-
xor << p1 | xor << p2 combine the shifted bits back = 100 | 00100000 = 00100100
-
Finally we xor with the original number to flip the bits at positions p1, p2 and the next n-1 bits result = 101111^100100 = 001011