program to swap two numbers using bitwise operators.

29 Dec 2022 Balmiki Kumar 0 C Programming

Swap Two Numbers using Bitwise Operators in C: Efficient Technique

A program to swap two numbers using bitwise operators means a computer program that exchanges the values of two variables (numbers) using bitwise operators. In this approach, the program uses the bitwise XOR (^) operator to swap the values of the variables without using a temporary variable.

The bitwise XOR operator (^) works on each bit of the variables and returns 1 if the corresponding bits are different, otherwise, it returns 0. By using the XOR operator, we can flip the bits of the variables to exchange their values.

Overall, this program provides an efficient way to swap two variables without using additional memory space.

Program: Program to Swap Two Numbers Using Bitwise Operators in C

#include<stdio.h>
int main() {
 int i = 65;
 int k = 120;
 printf("\n value of i=%d k=%d before swapping", i, k);
 i = i ^ k;
 k = i ^ k;
 i = i ^ k;
 printf("\n value of i=%d k=%d after swapping", i, k);
 return 0;
}

Explanation:

i = 65; binary equivalent of 65 is 0100 0001
k = 120; binary equivalent of 120 is 0111 1000
i = i^k;
i...0100 0001
k...0111 1000
-----------------------
val of i = 0011 1001
-----------------------
k = i^k
i...0011 1001
k...0111 1000
-----------------------------------------------------------------------------------
val of k = 0100 0001 binary equivalent of this is 65(that is the initial value of i)
-------------------------------------------------------------------------------------
i = i^k
i...0011 1001
k...0100 0001
---------------------------------------------------------------------------------------
val of i = 0111 1000 binary equivalent of this is 120 (that is the initial value of k)
--------------------------------------------------------------------------------------

 

Realted Seach


C Program to swap two numbers using a temporary variable.

program to swap two numbers without using a temporary variable.

program to swap two numbers using bitwise operators.

 

BY: Balmiki Kumar

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.