Click to See Complete Forum and Search --> : arithmetic with bit operations, addition subtraction


siqe
01-26-2003, 12:57 PM
I'm posting this for future forum searchers (or anyone that wants to see this now ) and not asking a question. I got a sequence of bitwise operations going that do addition and subtraction. I'm writing a math library and plan on putting in the code for doing all the calculations with multi-precision numbers, this is the beginning of my multi-precision number research.


#include<iostream>

short add( short a, short b );
short neg( short a );
short sub( short a, short b );

using namespace std;

int main()
{
short a=0,b,fchoice;
short (*func)(short, short);

while( true )
{
cout<<"1) Add"<<endl;
cout<<"2) Subtract"<<endl;
cout<<"3) Quit"<<endl;
cin>>fchoice;
switch( fchoice )
{
case 1: { func = add; break; }
case 2: { func = sub; break; }
case 3: { return 0; break; }
};
cout<<"Enter numbers..."<<endl;
cout<<"a: ";
cin>>a;
cout<<"b: ";
cin>>b;
cout<<"the operation yeids "<<func(a,b)<<endl;
}

return 0;
}

short add( short a, short b )
{
short carryflags = (a&b)<<1, sum=a^b, temp;
while( carryflags )
{
temp = carryflags;
carryflags = (sum & carryflags)<<1;
sum = sum ^ temp;
}
return sum;
}

short neg( short a )
{
int temp;
if(a==0)
return 0;
while( !(a&(temp)) )
{
a|=temp;
temp<<=1;
}
a^=temp;
return ~a;
}

short sub( short a, short b )
{
return add( a, neg( b ) );
}


[edit]: made some boo boos in the code