How to swap two bits in a given integer?

07 Jun, 2022
Given an integer n and two-bit positions p1 and p2 inside it, swap bits at the given positions. The given positions are from the least significant bit (lsb). For example, the position for lsb is 0.Examples: 
Input: n = 28, p1 = 0, p2 = 3Output: 21Explaination: 28 in binary is 11100.  If we swap 0’th and 3rd digits, we get 10101 which is 21 in decimal.
Input: n = 20, p1 = 2, p2 = 3Output: 24
We strongly recommend you minimize your browser and try this yourself first.Method 1: The idea is to first find the bits, then use XOR based swapping concept, i..e., to swap two numbers ‘x’ and ‘y’, we do x = x ^ y,  y = y ^ x, and x = x ^ y.
Below is the implementation of the above idea
C++
C
Java
C#
Javascript
Python3
// C++ program to swap bits in an integer#include<bits/stdc++.h>using namespace std; // This function swaps bit at positions p1 and p2 in an integer nint swapBits(unsigned int n, unsigned int p1, unsigned int p2){    /* Move p1'th to rightmost side */    unsigned int bit1 =  (n >> p1) & 1;     /* Move p2'th to rightmost side */    unsigned int bit2 =  (n >> p2) & 1;     /* XOR the two bits */    unsigned int x = (bit1 ^ bit2);     /* Put the xor bit back to their original positions */    x = (x << p1) | (x << p2);     /* XOR 'x' with the original number so that the       two sets are swapped */    unsigned int result = n ^ x;} /* Driver program to test above function*/int main(){    int res =  swapBits(28, 0, 3);    cout<<"Result = "<< res<<" ";    return 0;} // This code is contributed by pratham76.
// C program to swap bits in an integer#include<stdio.h> // This function swaps bit at positions p1 and p2 in an integer nint swapBits(unsigned int n, unsigned int p1, unsigned int p2){    /* Move p1'th to rightmost side */    unsigned int bit1 =  (n >> p1) & 1;     /* Move p2'th to rightmost side */    unsigned int bit2 =  (n >> p2) & 1;     /* XOR the two bits */    unsigned int x = (bit1 ^ bit2);     /* Put the xor bit back to their original positions */    x = (x << p1) | (x << p2);     /* XOR 'x' with the original number so that the       two sets are swapped */    unsigned int result = n ^ x;} /* Driver program to test above function*/int main(){    int res =  swapBits(28, 0, 3);    printf("Result = %d ", res);    return 0;}
// Java program to swap bits in an integerimport java.io.*; class GFG{     // This function swaps bit at// positions p1 and p2 in an integer nstatic int swapBits( int n, int p1, int p2){    /* Move p1'th to rightmost side */    int bit1 = (n >> p1) & 1;     /* Move p2'th to rightmost side */    int bit2 = (n >> p2) & 1;     /* XOR the two bits */    int x = (bit1 ^ bit2);     /* Put the xor bit back to    their original positions */    x = (x << p1) | (x << p2);     /* XOR 'x' with the original    number so that the    two sets are swapped */    int result = n ^ x;    return result;}     /* Driver code*/    public static void main (String[] args)    {        int res = swapBits(28, 0, 3);        System.out.println ("Result = " + res);    }} // This code is contributed by ajit..
// C# program to swap bits in an integerusing System;class GFG{   // This function swaps bit at  // positions p1 and p2 in an integer n  static int swapBits( int n, int p1, int p2)  {     /* Move p1'th to rightmost side */    int bit1 = (n >> p1) & 1;     /* Move p2'th to rightmost side */    int bit2 = (n >> p2) & 1;     /* XOR the two bits */    int x = (bit1 ^ bit2);     /* Put the xor bit back to    their original positions */    x = (x << p1) | (x << p2);     /* XOR 'x' with the original    number so that the    two sets are swapped */    int result = n ^ x;    return result;  }   /* Driver code*/  public static void Main(string[] args)  {    int res = swapBits(28, 0, 3);    Console.Write("Result = " + res);  }} // This code is contributed by rutvik_56.
<script>// javascript program to swap bits in an integer      // This function swaps bit at// positions p1 and p2 in an integer nfunction swapBits(n , p1 , p2){    /* Move p1'th to rightmost side */    var bit1 = (n >> p1) & 1;     /* Move p2'th to rightmost side */    var bit2 = (n >> p2) & 1;     /* XOR the two bits */    var x = (bit1 ^ bit2);     /* Put the xor bit back to    their original positions */    x = (x << p1) | (x << p2);     /* XOR 'x' with the original    number so that the    two sets are swapped */    var result = n ^ x;    return result;} /* Driver code*/var res = swapBits(28, 0, 3);document.write("Result = " + res);  // This code contributed by Princi Singh</script>
# Python3 program for the above approach # This function swaps bit at positions p1 and p2 in an integer ndef swapBits(n, p1, p2):     # Move p1'th to rightmost side    bit1 = (n >> p1) & 1     # Move p2'th to rightmost side    bit2 = (n >> p2) & 1     # XOR the two bits    x = (bit1 ^ bit2)     # Put the xor bit back to their original positions    x = (x << p1) | (x << p2)     # XOR 'x' with the original number so that the    # two sets are swapped    result = n ^ x    return result  # Driver program to test above functionif __name__ == '__main__':    res = swapBits(28, 0, 3)    print("Result = ", res) # This code is contributed by nirajgusain5
Result = 21 
Time Complexity: O(1)Auxiliary Space: O(1) 
C++
C
Java
Python
C#
Javascript
//C++ code for swapping given bits of a number#include<iostream>using namespace std;int swapBits(int n, int p1, int p2){   //left-shift 1 p1 and p2 times   //and using XOR  if (((n & (1 << p1)) >> p1) ^ ((n & (1 << p2)) >> p2))  {    n ^= 1 << p1;    n ^= 1 << p2;  }  return n;} //Driver Codeint main(){    cout << "Result = " << swapBits(28, 0, 3);    return 0;}
//C code for swapping given bits of a number#include<stdio.h>int swapBits(int n, int p1, int p2){    //left-shift 1 p1 and p2 times    //and using XOR    if (((n & (1 << p1)) >> p1) ^ ((n & (1 << p2)) >> p2))    {      n ^= 1 << p1;      n ^= 1 << p2;    }    return n;} //Driver Codeint main(){    printf("Result = %d", swapBits(28, 0, 3));    return 0;}
// Java code for swapping// given bits of a numberimport java.util.*;class Main{   public static int swapBits(int n,                           int p1,                           int p2){  //left-shift 1 p1 and  // p2 times and using XOR  int temp = ((n & (1 << p1)) >> p1) ^ ((n & (1 << p2)) >> p2);  if (temp >= 1)  {    n ^= 1 << p1;    n ^= 1 << p2;  }  return n;}    // Driver codepublic static void main(String[] args){  System.out.print("Result = " +                   swapBits(28, 0, 3));}} // This code is contributed by divyeshrabadiya07
# Python code for swapping given bits of a numberdef swapBits(n, p1, p2):   # left-shift 1 p1 and p2 times  # and using XOR    if ((n & (1 << p1)) >> p1) ^ ((n & (1 << p2)) >> p2):        n ^= 1 << p1        n ^= 1 << p2    return n # Driver Codeprint("Result =",swapBits(28, 0, 3)) # This code is contributed by rag2127
// C# code for swapping given bits of a numberusing System;class GFG {     static int swapBits(int n, int p1, int p2)    {        // left-shift 1 p1 and p2 times        // and using XOR    int temp = ((n & (1 << p1)) >> p1) ^ ((n & (1 << p2)));    if (temp >= 1)    {            n ^= 1 << p1;            n ^= 1 << p2;    }    return n;    }     // Driver code    static void Main()    {        Console.WriteLine("Result = " + swapBits(28, 0, 3));    }} // This code is contributed by divyesh072019
<script>     // JavaScript code for swapping given bits of a number         function swapBits(n, p1, p2)    {        temp = ((n & (1 << p1)) >> p1) ^ ((n & (1 << p2)) >> p2);        if (temp >= 1)        {          n ^= 1 << p1;          n ^= 1 << p2;        }        return n;    }     document.write("Result = " + swapBits(28, 0, 3));     </script>
Result = 21
Time Complexity: O(1)Auxiliary Space: O(1)
Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above
jit_t
SHUBHAMSINGH10
nidhi_biet
yashbeersingh42
divyeshrabadiya07
rag2127
divyesh072019
rutvik_56
pratham76
suresh07
princi singh
nirajgusain5
subham348
mohammad shuaib sidd
harendrakumar123
Bit Magic
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.