Swap bits in a given number

Last Updated : 2 Jul, 2026

Given an integer x and three integers p1, p2, and n, swap the n consecutive bits starting from position p1 with the n consecutive bits starting from position p2 in the binary representation of x.

  • Bit positions are numbered from right to left using 0-based indexing, where the least significant bit (LSB) is at position 0.
  • The two bit blocks are guaranteed to be non-overlapping.

Return the number obtained after swapping the two bit blocks.

Examples:

Input: x = 47, p1 = 1, p2 = 5, n = 3
Output: 227
Explanation: The binary representation of 47 is 00101111. The 3 consecutive bits starting at position 1 are 111, and the 3 starting at position 5 are 001. Swapping these two changes the binary to 11100011, which is equal to 227 in decimal.

Input: x = 28, p1 = 0, p2 = 3, n = 2
Output: 7
Explanation: The binary representation of 28 is 11100. The 2 bits starting at position 0 are 00, and the 2 starting at position 3 are 11. After swapping these two, the binary representation becomes 00111, which is 7 in decimal.

Try It Yourself
redirect icon

Using XOR - O(1) time and O(1) space

The idea is to first extract the two groups of n consecutive bits starting at positions p1 and p2. Compute the XOR of these two groups to identify the bit positions where they differ. Then, place these differing bits back at their original positions and XOR them with the original number. Since XOR flips only the differing bits, the two bit groups get swapped while all other bits remain unchanged.

  • Extract the n bits starting at positions p1 and p2.
  • Compute the XOR of the two extracted bit groups.
  • Shift the XOR result back to positions p1 and p2.
  • XOR this value with the original number to swap the two bit groups.
  • Return the modified number.
C++
#include <bits/stdc++.h>
using namespace std;

// Function to swap bits in a given number
int swapBits(int x, int p1, int p2, int n) {
    
    // Move all bits of first set to rightmost side 
    int set1 = (x >> p1) & ((1 << n) - 1);

    // Move all bits of second set to rightmost side 
    int set2 = (x >> p2) & ((1 << n) - 1);

    // Xor the two sets 
    int xorVal = (set1 ^ set2);

    // Put the Xor bits back to their original positions 
    xorVal = (xorVal << p1) | (xorVal << p2);

    // Xor the 'Xor' with the original number so that the 
    // two sets are swapped 
    int result = x ^ xorVal;

    return result;
}

int main() {
    int x = 47;
    int p1 = 1;
    int p2 = 5;
    int n = 3;
    int res = swapBits(x,p1,p2,n);
    cout << res;
    return 0;
}
Java
class GFG {

    // Function to swap bits in a given number
    static int swapBits(int x, int p1, int p2, int n) {

        // Move all bits of first set to rightmost side
        int set1 = (x >> p1) & ((1 << n) - 1);

        // Move all bits of second set to rightmost side
        int set2 = (x >> p2) & ((1 << n) - 1);

        // Xor the two sets
        int xorVal = (set1 ^ set2);

        // Put the Xor bits back to their original positions
        xorVal = (xorVal << p1) | (xorVal << p2);

        // Xor the 'Xor' with the original number so that the
        // two sets are swapped
        int result = x ^ xorVal;

        return result;
    }

    public static void main(String[] args) {
        int x = 47;
        int p1 = 1;
        int p2 = 5;
        int n = 3;

        int res = swapBits(x, p1, p2, n);
        System.out.println(res);
    }
}
Python
# Function to swap bits in a given number
def swapBits(x, p1, p2, n):

    # Move all bits of first set to rightmost side
    set1 = (x >> p1) & ((1 << n) - 1)

    # Move all bits of second set to rightmost side
    set2 = (x >> p2) & ((1 << n) - 1)

    # Xor the two sets
    xorVal = set1 ^ set2

    # Put the Xor bits back to their original positions
    xorVal = (xorVal << p1) | (xorVal << p2)

    # Xor the 'Xor' with the original number so that the
    # two sets are swapped
    result = x ^ xorVal

    return result


if __name__ == "__main__":
    x = 47
    p1 = 1
    p2 = 5
    n = 3

    res = swapBits(x, p1, p2, n)
    print(res)
C#
using System;

class GFG
{
    // Function to swap bits in a given number
    static int swapBits(int x, int p1, int p2, int n)
    {
        // Move all bits of first set to rightmost side
        int set1 = (x >> p1) & ((1 << n) - 1);

        // Move all bits of second set to rightmost side
        int set2 = (x >> p2) & ((1 << n) - 1);

        // Xor the two sets
        int xorVal = (set1 ^ set2);

        // Put the Xor bits back to their original positions
        xorVal = (xorVal << p1) | (xorVal << p2);

        // Xor the 'Xor' with the original number so that the
        // two sets are swapped
        int result = x ^ xorVal;

        return result;
    }

    static void Main()
    {
        int x = 47;
        int p1 = 1;
        int p2 = 5;
        int n = 3;

        int res = swapBits(x, p1, p2, n);
        Console.WriteLine(res);
    }
}
JavaScript
// Function to swap bits in a given number
function swapBits(x, p1, p2, n) {

    // Move all bits of first set to rightmost side
    let set1 = (x >> p1) & ((1 << n) - 1);

    // Move all bits of second set to rightmost side
    let set2 = (x >> p2) & ((1 << n) - 1);

    // Xor the two sets
    let xorVal = set1 ^ set2;

    // Put the Xor bits back to their original positions
    xorVal = (xorVal << p1) | (xorVal << p2);

    // Xor the 'Xor' with the original number so that the
    // two sets are swapped
    let result = x ^ xorVal;

    return result;
}

// Driver code
let x = 47;
let p1 = 1;
let p2 = 5;
let n = 3;

let res = swapBits(x, p1, p2, n);
console.log(res);

Output
227

Checking Each bit - O(1) time and O(1) space

The idea is to perform a bit-by-bit swap by iterating through each of the n positions, checking if the corresponding bits at the two positions differ, and if they do, flipping both bits to effectively swap their values - this approach handles the swap one bit at a time rather than operating on the entire bit sequences in a single operation.

  • Repeat the following steps for all n consecutive bit positions.
  • Create bit masks for the current positions p1 and p2.
  • Extract the bits at these positions using the masks.
  • If the two bits are different, clear the set bit and set the corresponding bit at the other position to swap them.
  • Increment p1 and p2 to process the next pair of bits.
  • After all n bit pairs have been processed, return the modified number.
C++
#include <bits/stdc++.h>
using namespace std;

// Function to swap bits in a given number
int swapBits(int x, int p1, int p2, int n) {

    int shift1, shift2, val1, val2;

    // Process all n bit positions
    while (n--) {

        // Create masks for positions p1 and p2
        shift1 = 1 << p1;
        shift2 = 1 << p2;

        // Extract the bits at positions p1 and p2
        val1 = x & shift1;
        val2 = x & shift2;

        // Swap only if the bits are different
        if ((!val1 && val2) || (val1 && !val2)) {

            // If bit at p1 is set
            if (val1) {

                // Clear bit at p1
                x &= ~shift1;

                // Set bit at p2
                x |= shift2;
            }
            else {

                // Clear bit at p2
                x &= ~shift2;

                // Set bit at p1
                x |= shift1;
            }
        }

        // Move to the next pair of bits
        p1++;
        p2++;
    }

    return x;
}

int main() {

    int x = 28;
    int p1 = 0;
    int p2 = 3;
    int n = 2;

    cout << swapBits(x, p1, p2, n);

    return 0;
}
Java
class GFG {
    
    // Function to swap bits in a given number
    public static int swapBits(int x, int p1, int p2, int n) {
        int shift1, shift2, val1, val2;

        // Process all n bit positions
        while (n-- > 0) {
            // Create masks for positions p1 and p2
            shift1 = 1 << p1;
            shift2 = 1 << p2;

            // Extract the bits at positions p1 and p2
            val1 = x & shift1;
            val2 = x & shift2;

            // Swap only if the bits are different
            if ((!(val1!= 0) && val2!= 0) || (val1!= 0 &&!(val2!= 0))) {
                
                // If bit at p1 is set
                if (val1!= 0) {
                    
                    // Clear bit at p1
                    x &= ~shift1;
                    
                    // Set bit at p2
                    x |= shift2;
                } else {
                    
                    // Clear bit at p2
                    x &= ~shift2;
                    
                    // Set bit at p1
                    x |= shift1;
                }
            }

            // Move to the next pair of bits
            p1++;
            p2++;
        }

        return x;
    }

    public static void main(String[] args) {
        int x = 28;
        int p1 = 0;
        int p2 = 3;
        int n = 2;

        System.out.println(swapBits(x, p1, p2, n));
    }
}
Python
def swapBits(x, p1, p2, n):
    shift1 = shift2 = val1 = val2 = 0
    
    # Process all n bit positions
    while n > 0:
        n -= 1
        
        # Create masks for positions p1 and p2
        shift1 = 1 << p1
        shift2 = 1 << p2
        
        # Extract the bits at positions p1 and p2
        val1 = x & shift1
        val2 = x & shift2
        
        # Swap only if the bits are different
        if ((not val1 and val2) or (val1 and not val2)):
            
            # If bit at p1 is set
            if val1:
                
                # Clear bit at p1
                x &= ~shift1
                
                # Set bit at p2
                x |= shift2
            else:
                
                # Clear bit at p2
                x &= ~shift2
                
                # Set bit at p1
                x |= shift1
        
        # Move to the next pair of bits
        p1 += 1
        p2 += 1
    
    return x

if __name__ == '__main__' :
    x = 28
    p1 = 0
    p2 = 3
    n = 2
    
    print(swapBits(x, p1, p2, n))
C#
using System;

class GFG {
    
    // Function to swap bits in a given number
    public static int swapBits(int x, int p1, int p2, int n) {
        int shift1, shift2, val1, val2;

        // Process all n bit positions
        while (n-- > 0) {
            // Create masks for positions p1 and p2
            shift1 = 1 << p1;
            shift2 = 1 << p2;

            // Extract the bits at positions p1 and p2
            val1 = x & shift1;
            val2 = x & shift2;

            // Swap only if the bits are different
            if ((!(val1!= 0) && val2!= 0) || (val1!= 0 &&!(val2!= 0))) {
                
                // If bit at p1 is set
                if (val1!= 0) {
                    
                    // Clear bit at p1
                    x &= ~shift1;
                    
                    // Set bit at p2
                    x |= shift2;
                } else {
                    
                    // Clear bit at p2
                    x &= ~shift2;
                    
                    // Set bit at p1
                    x |= shift1;
                }
            }

            // Move to the next pair of bits
            p1++;
            p2++;
        }

        return x;
    }

    public static void Main() {
        int x = 28;
        int p1 = 0;
        int p2 = 3;
        int n = 2;

        Console.WriteLine(swapBits(x, p1, p2, n));
    }
}
JavaScript
function swapBits(x, p1, p2, n) {
    let shift1, shift2, val1, val2;

    // Process all n bit positions
    while (n-- > 0) {
        
        // Create masks for positions p1 and p2
        shift1 = 1 << p1;
        shift2 = 1 << p2;

        // Extract the bits at positions p1 and p2
        val1 = x & shift1;
        val2 = x & shift2;

        // Swap only if the bits are different
        if ((!(val1!== 0) && val2!== 0) || (val1!== 0 &&!(val2!== 0))) {
            
            // If bit at p1 is set
            if (val1!== 0) {
                
                // Clear bit at p1
                x &= ~shift1;
                
                // Set bit at p2
                x |= shift2;
            } else {
                
                // Clear bit at p2
                x &= ~shift2;
                
                // Set bit at p1
                x |= shift1;
            }
        }

        // Move to the next pair of bits
        p1++;
        p2++;
    }

    return x;
}

// Driver code
const x = 28;
const p1 = 0;
const p2 = 3;
const n = 2;

console.log(swapBits(x, p1, p2, n));

Output
7
Comment