C program to swap two bits of a 32-bit integer number

Here, we are going to learn how to swap two bits of a 32-bit integer number in C programming language?
Submitted by Nidhi, on July 31, 2021

Problem statement

Read an integer number and bit positions. Then swap bit positions of a given number using C program.

C program to swap two bits of a 32-bit integer number

The source code to swap two bits of a 32-bit integer number is given below. The given program is compiled and executed using GCC compile on UBUNTU 18.04 OS successfully.

```// C program to swap two bits of a
// 32-bit integer number

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char* argv[])
{
int num = 0;
int pos1 = 0;
int pos2 = 0;

int i = 0;

printf("Enter Number: ");
scanf("%d", &num);

printf("Enter position1: ");
scanf("%d", &pos1);

printf("Enter position2: ");
scanf("%d", &pos2);

printf("Binary number before swapping bits: \n");
for (i = 31; i >= 0; i--) {
if (num & (1 << i))
printf("1");
else
printf("0");
}

if (((num & (1 << pos1)) >> pos1) ^ ((num & (1 << pos2)) >> pos2)) {
num ^= (1 << pos1);
num ^= (1 << pos2);
}

printf("\nResult is: %d\n", num);
printf("Binary number after swapping bits: \n");
for (i = 31; i >= 0; i--) {
if (num & (1 << i))
printf("1");
else
printf("0");
}

printf("\n");

return 0;
}
```

Output

```RUN 1:
Enter Number: 191
Enter position1: 5
Enter position2: 6
Binary number before swapping bits:
00000000000000000000000010111111
Result is: 223
Binary number after swapping bits:
00000000000000000000000011011111

RUN2:
Enter Number: 8
Enter position1: 2
Enter position2: 3
Binary number before swapping bits:
00000000000000000000000000001000
Result is: 4
Binary number after swapping bits:
00000000000000000000000000000100

RUN 3:
Enter Number: 2730
Enter position1: 1
Enter position2: 2
Binary number before swapping bits:
00000000000000000000101010101010
Result is: 2732
Binary number after swapping bits:
00000000000000000000101010101100
```

Explanation

Here, we read an integer number and bit positions from the user. Then we interchanged the bits from given positions. After that, we printed the result on the console screen.