LaVic schrieb:
I am trying to add two binary numbers in the form of two arrays.
This seems like an awful waste. The following is a little example of
how to do it using bit-wise operations on unsigned ints. The program
adds two positive integers. It could be refined in a lot of ways. It
seems to work correctly, but no guarantees. I tried to get it to show
that overflow occurred if the sum went out of range, but it doesn't
work, and I don't have time to work on it anymore. I hope you find it
helpful.
Laurence Finston
**************************************
int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
char c[8];
unsigned int mask = 1;
unsigned long carry_mask = 1; /* Wasting 31 bits here, but what the
heck. */
unsigned int operand_1 = 0;
unsigned int operand_2 = 0;
unsigned int result = 0;
unsigned short uint_size = sizeof(unsigned int) * 8; /* Assume 8
bits per byte
(a pretty
safe assumption). */
unsigned short curr_pos = 0;
while (true)
{
mask = 1;
carry_mask = 0;
result = 0;
#if 0
unsigned int max_mask = ~carry_mask;
cout << "max_mask == " << max_mask << endl;
#endif
cout << "Enter operand 1: ";
cin >operand_1;
cout << "Enter operand 2: ";
cin >operand_2;
for (curr_pos = 0; curr_pos < uint_size; ++curr_pos)
{
cout << "At beginning of loop:\n"
<< "curr_pos == " << curr_pos
<< endl
<< "mask == " << mask
<< endl
<< "carry_mask == " << carry_mask
<< endl;
if (mask & carry_mask & operand_1 & operand_2)
{
carry_mask <<= 1;
result |= mask;
}
else if (mask & carry_mask & (operand_1 | operand_2))
{
carry_mask <<=1;
}
else if (mask & carry_mask)
{
carry_mask = 0;
result |= mask;
}
else if (mask & ~carry_mask & operand_1 & operand_2)
{
carry_mask = mask << 1;
}
else if (mask & ~carry_mask & (operand_1 | operand_2))
{
carry_mask = 0;
result |= mask;
}
cout << "At end of loop:"
<< endl
<< "result == " << result << endl
<< "carry_mask == " << carry_mask
<< endl
<< "***************"
<< endl << endl;
mask <<= 1;
} /* |for| */
cout << "result == " << result << endl << endl;
cout << "carry_mask == " << carry_mask << endl;
/* This doesn't work. Don't have time to play with it anymore.
*/
if (carry_mask)
cout << "Overflow occurred.";
else
cout << "No overflow occurred.";
cout << "Enter `x' to quit, or any other character to continue:
";
cin >c;
if (!strcmp(c, "x"))
break;
} /* |while (true)| */
return 0;
}