Swapping numbers using bitwise operator in C


Problem

How to swap the numbers using the bitwise operator in the C programming language?

Solution

The compiler swap the given numbers, first, it converts the given decimal number into binary equivalent then it performs a bitwise XOR operation to exchange the numbers from one memory location to another.

Algorithm

START
Step 1: declare two variables a and b
Step 1: Enter two numbers from console
Step 2: swap two numbers by using BITWISE operator
        a=a^b
        b=a^b
        a=a^b
Step 3: Print a and b values
STOP

Program

 Live Demo

#include<stdio.h>
int main(){
   int a,b;
   printf("enter the values for a and b:");
   scanf("%d%d",&a,&b);
   printf("value of a=%d and b=%d before swap
",a,b);    a= a^b;    b= a^b;    a= a^b;    printf("value of a=%d and b=%d after swap",a,b);    return 0; }

Output

enter the values for a and b:24 56
value of a=24 and b=56 before swap
value of a=56 and b=24 after swap
Explanation:
a=24 binary equivalent of 24 =011000
b=56 binary equivalent of 56= 111000
a= a^b = 100000
b=a^b=100000 ^ 111000 =011000
a=a^b=100000 ^ 011000 = 111000
Now a=111000 decimal equivalent =56
b= 011000 decimal equivalent = 24

Updated on: 05-Mar-2021

13K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements