M
mohangupta13
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??
Thanks
Mohan Gupta
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??
Thanks
Mohan Gupta