#include<iostream>
using namespace std;
int add(int x,int y)
{
int ans=0;
int carry=0;
for(int i=0;i<=31;i++)
{
int p = (1<<i)&x;
int q = (1<<i)&y;
int r = p ^ q;
r = r^(carry<<i);
ans = r | ans;
if(p&q || p&(carry<<i) || q&(carry<<i))
carry = 1;
else
carry =0;
}
return (ans);
}
int main()
{
int x,y;
x=-2;y=6;
//add(4,6);
cout<<endl<<add(x,y)<<endl;
return 0;
}
Actually, I am trying to add bit by bit. When number is negative, it is represented by 2's compliment. But, here I am using the 32th leftmost bit. Isn't it wrong?
It is giving corrent for small numbers but for large numbers like (-2222222,6) giving wrong answer. Can anyone explain why?
Thanks a lot in advance.