mohangupta13 <(E-Mail Removed)> wrote:

> On Dec 14, 6:34Â*pm, Tom St Denis <(E-Mail Removed)> wrote:

> > On Dec 14, 8:12Â*am, mohangupta13 <(E-Mail Removed)> wrote:

> >

> > > Hello all , I just came across an interesting question .

> > > Q. Add two numbers using bit operations in C?

> >

> > > I came up with the below solution .Though it does work , But I believe

> > > there must be a better way to solve this question . Please provide

> > > your inputs .

> >

> > > int add(int a,int b){

> >

> > > int c=0; //answer

> > > int mask=0,carry=0,sum=0,i;

> > > int a_bit=0,b_bit=0;

> > > for(i=0;i<(pos-1);i++){//pos-1 to leave the MSB as its a sign bit

> > > Â* Â* Â* Â* mask=1<<i;

> > > Â* Â* Â* Â* a_bit=a&mask?1:0;

> > > Â* Â* Â* Â* b_bit=b&mask?1:0;

> > > Â* Â* Â* Â* sum=a_bit+b_bit+carry;

> > > Â* Â* Â* Â* switch(sum){

> > > Â* Â* Â* Â* Â* Â* Â* Â* case 0: carry=0;//this bit in c is already 0

> > > Â* Â* Â* Â* Â* Â* Â* Â* Â* Â* Â* Â* break;

> > > Â* Â* Â* Â* Â* Â* Â* Â* case 1: //make this bit in c 1

> > > Â* Â* Â* Â* Â* Â* Â* Â* Â* Â* Â* Â* c|=mask;

> > > Â* Â* Â* Â* Â* Â* Â* Â* Â* Â* Â* Â* carry=0;

> > > Â* Â* Â* Â* Â* Â* Â* Â* Â* Â* Â* Â* break;

> > > Â* Â* Â* Â* Â* Â* Â* Â* case 2: //make this bit zero and carry=1

> > > Â* Â* Â* Â* Â* Â* Â* Â* Â* Â* Â* Â* //this bit is already zero

> > > Â* Â* Â* Â* Â* Â* Â* Â* Â* Â* Â* Â* carry=1;

> > > Â* Â* Â* Â* Â* Â* Â* Â* Â* Â* Â* Â* break;

> > > Â* Â* Â* Â* Â* Â* Â* Â* case 3: //make this bit 1 and carry =1

> > > Â* Â* Â* Â* Â* Â* Â* Â* Â* Â* Â* Â* c|=mask;

> > > Â* Â* Â* Â* Â* Â* Â* Â* Â* Â* Â* Â* carry=1;

> > > Â* Â* Â* Â* Â* Â* Â* Â* Â* Â* Â* Â* break;

> > > Â* Â* Â* Â* Â* Â* Â* Â* default: printf("this must not have happened \n");

> > > Â* Â* Â* Â* Â* Â* Â* Â* Â* Â* Â* Â* Â*return -1;

> > > Â* Â* Â* Â* Â* Â* Â* Â* }

> >

> > > }

> > > return c;

> > > }

> >

> > > And one more thing does the C standard specify that for an integral

> > > number the MSB is a sign bit or does it say something Â*about the bit

> > > representation of types??

> >

> > You want to do some variant of

> >

> > sum[i] Â* Â* = a[i] ^ b[i] ^ carry[i]

> > carry[i+1] = (a[i] & carry[i]) | (b[i] & carry[i]) | (a[i] & b[i])

> >

> but creating this array representation of 'a' and 'b' and then

> converting 'c' from an array to an integer is more troublesome than

> what i wrote i believe.
But your solution is cheating since you use an addition

> > > sum=a_bit+b_bit+carry;
just that you add bits instead of the whole number while you

explicitely wrote that you had to use bitwise operators which

'+' isn't. By the way, the topmost bit of your result will

never be set, whatever the input...

Regards, Jens

--

\ Jens Thoms Toerring ___

http://www.velocityreviews.com/forums/(E-Mail Removed)
\__________________________

http://toerring.de