# How to swap two bits in a given integer?

Given an integer n and two bit positions p1 and p2 inside it, swap bits at the given positions. The given positions are from least significant bit (lsb). For example, the position for lsb is 0.

Examples:

```Input: n = 28, p1 = 0, p2 = 3
Output: 21
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 = 3
Output: 24
```

We strongly recommend you to minimize your browser and try this yourself first.

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 C implementation.

```// C program to swap bits in an intger
#include<stdio.h>

// This function swaps bit at positions p1 and p2 in an integer n
int 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 ^ bitt2);

/* 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;
}

/* Drier program to test above function*/
int main()
{
int res =  swapBits(28, 0, 3);
printf("\nResult = %d ", res);
return 0;
}
```

Output:

`Result = 24`

# GATE CS Corner    Company Wise Coding Practice

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.
4 Average Difficulty : 4/5.0
Based on 2 vote(s)