Write code for adding two n-bit and assume that your code will run on a machine which doesn’t have ADD instruction which means that you can’t use the + operator.
Approach : Make a 1 bit adder and then cascade it to work for n bits i.e. assuming that we are adding 32 bit numbers then it will work for 32 bits.
To figure out the equation for a 1 bit adder we will write the truth table for a 1-bit adder.
A B Sum Carry
0 0 0 0
0 1 1 0
1 1 0 1
1 0 1 0
So now if you look the SUM column is A’B + AB’ which is (A XOR B)
Carry is (A AND B)
Code for the above approach
int
Nbitadder (int no1, int no2)
{
Int carry = 0;
Int totalSum = 0;
For (i=0; I < sizeof(int) ; i++)
{
// Shift the bit to get it to the first position for both numbers
Bit1no1 = no1 >> i;
Bit1no2 = no2 >> i;
// Mask out all the other bits except the first bit.
Bit1no1 = bit1no1 & 0x00000001;
Bit1no2 = bit2no2 & 0x00000001;
If ( carry == 0)
{
Sum = bit1no1 XOR bit1no2; // Add the two bits
Carry = bit1no1 AND bit1no2; // check if there is any carry generated out of the two bits
Totasum = (totasum | (sum << i)); // left shift the result to get it to the correct bit position
}
Else if (carry > 0)
{
Sum = bit1no1 XOR carry; // Add the carry to the first bit
Carry = bit1no1 AND carry; // save the new carry if generated out of this addition
Sum = Sum XOR bit1no2; // add this new sum to the second bit
Carry = Sum AND bit1no2;
Totasum = (totasum | (sum << i)); // left shift the sum to put it to correct bit position and then OR it with the result.
}
}
Return Totasum;
}
No comments:
Post a Comment