Swap two numbers using bitwise operator in C
In this post, you will learn how to swap two numbers using the bitwise operator in C programming language. Such a type of question is generally asked in programming interviews, the interviewer may ask to write a program for swapping of two numbers using a particular way.
C program to swap two numbers using Bitwise XOR
Here, we have used the bitwise XOR operator to swap two variables. The XOR of two numbers x and y returns a number that has all the bits as 1 wherever bits of x and y differ. For example, XOR of 10 (binary 1010) and 5 (binary 0101) is 1111.
#include <stdio.h>
int main()
{
int x = 40, y = 55;
printf("Before swapping: x = %d, y = %d", x, y);
x = x ^ y;
y = x ^ y;
x = x ^ y;
printf("\nAfter Swapping: x = %d, y = %d", x, y);
return 0;
}
Output of the above code:
Before swapping: x = 40, y = 55
After Swapping: x = 55, y = 40
Related Articles
Average of two numbers in CSwapping of two numbers in C using pointers
Armstrong number in C using function
Binary to decimal C program
Sum of array elements in C
Random number generator in C
Factorial program in c using while loop
Student mark sheet program in C
C program to sort names in alphabetical order
C program to find largest number in an array
Print first 10 natural numbers using while loop in C
Simple calculator program in C
C program for simple interest
Swap two numbers without using third variable in C
Radix sort program in C
Bit stuffing program in C
Bubble sort program in C
Decimal to hexadecimal in C
Hexadecimal to decimal in C
Quick sort program in C