Tuesday, October 13, 2015

Addition and subtraction using Bitwise operators

#include <iostream>
using namespace std;

int add(int a,int b)
{
int sum;
int car;
do
{

sum=a^b;
car=a&b;
a=sum;
b=car<<1;
}
while(b!=0);
return a;
}
int sub(int a,int b)
{

do
{
int car;
car=(~a)&b;
a=a^b;
b=car<<1;
}
while(b!=0);
return a;
}
int main()
{
unsigned int a=5;
int b=2;
cout<<add(a,b)<<"\n";
cout<<sub(a,b);
return 0;
}

No comments:

Post a Comment

Contributors

Translate