The program adds two binary numbers in two' s complement ignoring the overflow for a constant size of bits. I am trying to generalize the program by taking input from the user in a single line without memory wastage. Is there any way to achieve this?
#include<iostream.h>
#include<conio.h>
void main ()
{
const int size=9;
enum bool {a=0, b=1};
bool carry,dummy;
bool array[size]={0,0,1,1,1,1,1,0,1};
bool reg[size]= {1,0,1,1,1,0,1,0,1};
for (int i=(size-1); i>=0 ; i--)
{
dummy=reg[i];
reg[i]= (!reg[i]) && (array[i] !=carry) || reg[i] && (array[i]==carry);
carry=(array[i]&&dummy) || (dummy&&carry) || (array[i]&&carry);
}
for (int j=0 ; j<size ; j++)
{
cout<<reg[j];
}
}
-
\$\begingroup\$ For size, use constexpr, rather than const. \$\endgroup\$JNS– JNS2015年04月08日 16:29:53 +00:00Commented Apr 8, 2015 at 16:29
2 Answers 2
Everything is in
main
. You need to makebinary_add
function, which only adds things. It may even return interesting things (aka condition flags).carry
is not initialized.I don't see how do you use
enum bool
.I don't see why do you
#include <conio.h>
Be consistent with spaces.
carry
computation is very crowded. Make it(array[i] && dummy) || (dummy && carry) || (array[i] && carry)
Rather than converting to what is basically an integer array, which uses 16 bits per element, you'll find it much easier and more memory efficient to use a bitset<>
, which stores 1 bit per element. With this you can cheat and convert the decimal addition to a bitset:
const size_t BIT_LENGTH = 9;
bitset<BIT_LENGTH> AddBinary(int numA, int numB)
{
bitset<BIT_LENGTH> answer(numA + numB);
return answer;
}
Or if you truly want bit manipulation something like this would work:
bitset<BIT_LENGTH> AddBinary(int numA, int numB)
{
bitset<BIT_LENGTH> binaryA(numA);
bitset<BIT_LENGTH> binaryB(numB);
bitset<1> carry;
for (int i = 0; i < BIT_LENGTH; i++)
{
bitset<2> temp(binaryA[i] + binaryB[i] + carry[0]);
binaryA[i] = temp[0];
carry[0] = temp[1];
}
return binaryA;
}
Now you can get the user to input integers and displaying the results is a simple matter of:
cout << AddBinary(numa,numb);