Bitwise Operation

Bitwise Operation in C


Addition and multiplication by 2 using bitwise Operation

#include<stdio.h>
main()
{
 int a;
 printf(“Enter an”);
 scanf(“%d”,&a);
 printf(“%d*2=%d n”,a,a<<1);
 printf(“%d/2=%d n”,a,a>>1);
}
Output
Enter a
10
10*2=20
10/2=5

Swap two numbers using bitwise Operation
 #include <stdio.h>
int main()
{
 int num1,num2;
 printf(“Enter num1n”);
 scanf(“%d”,&num1);
 printf(“Enter num2n”);
 scanf(“%d”,&num2);
 printf(“Before Swapping Number 1= %d,Number 2= %dn”,num1,num2);
 num1=num1^num2;
 num2=num1^num2;
 num1=num1^num2;
 printf(“x=%dn”,num1);
 printf(“After Swapping Number 1= %d,Number 2= %dn”,num1,num2);
 return 0;
}
Output
 Enter num1

20
Enter num2
25
Before Swapping Number 1= 20,Number 2= 25
x=25
After Swapping Number 1= 25,Number 2= 20

Leave a Comment