2
\$\begingroup\$

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];
 }
}
200_success
146k22 gold badges190 silver badges478 bronze badges
asked Apr 8, 2015 at 16:14
\$\endgroup\$
1
  • \$\begingroup\$ For size, use constexpr, rather than const. \$\endgroup\$ Commented Apr 8, 2015 at 16:29

2 Answers 2

4
\$\begingroup\$
  • Everything is in main. You need to make binary_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)
    
answered Apr 8, 2015 at 16:43
\$\endgroup\$
3
\$\begingroup\$

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);
answered Apr 8, 2015 at 18:20
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.