Program Code: 1 2 3 4 5 6 7 8 9 10 11
#include <stdio.h> int main() { int i = 65; int k = 120; printf(" value of i=%d k=%d before swapping", i, k); i = i ^ k; k = i ^ k; i = i ^ k; printf(" 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)
C Program to Swap two Numbers using Bitwise Operators
This C Program Swaps two Numbers using Bitwise operators. Here is source code of the C Program to Swap two Numbers using Bitwise operators. The C program is successfully compiled and run on a Linux system. The program output is also shown below.
1. /* 2. * C Program to Swap two Numbers using Bitwise operators 3. */ 4. #include <stdio.h> 5. #include <string.h> 6. 7. /* Function Prototype */ 8. void swap(int*, int *); 9. 10. void main() 11. { 12. int num1, num2; 13. printf("\nEnter two numbers:"); 14. scanf("%d %d", &num1, &num2); 15. printf("\nThe numbers before swapping are Number1= %d Number2 = %d", num1, num2); 16. swap(&num1, &num2); /* Call by Reference to function swap */ 17. printf("\nThe numbers after swapping are Number1= %d Number2 = %d", num1, num2); 18. } 19. 20. /* Code to swap two numbers using bitwise operator */ 21. void swap(int *x, int *y) 22. { 23. *x = *x ^ *y; 24. *y = *x ^ *y; 25. *x = *x ^ *y; 26. }
$ cc bit27.c $ a.out Enter two numbers:45 76 The numbers before swapping are Number1= 45 Number2=76 The numbers after swapping are Number1= 76 Number2=45