Hi all,
I've been writing a program to add two character arrays, which both hold a binary number and using binary arithmetic, stores the final value in another character array.
So far, i've been pretty successful. I seem to be having trouble on the final output though. Maybe I'm having a brain fart, I dunno. But the output displays the correct binary numbers but along side various random characters.
Preprocessor commands and function prototypes
Code:
#include <iostream>
#include <math.h>
void addBinaries(char[], char[], char[]);
driver function
Code:
int main()
{
const int MAX_ARR = 255;
char arrBinOne[MAX_ARR], arrBinTwo[MAX_ARR], arrFinal[MAX_ARR];
std::cout << "Please enter two binary numbers to be added..." << std::endl
<< "Enter 1:";
std::cin >> arrBinOne;
std::cout << "Enter 2:";
std::cin >> arrBinTwo;
addBinaries (arrBinOne, arrBinTwo, arrFinal);
//output arrays
std::cout << "\n" << arrBinOne << " + " << arrBinTwo << " = " << arrFinal << std::endl;
system("PAUSE");
return 0;
}
addBinaries definition
Code:
void addBinaries(char binOne[], char binTwo[], char final[])
{
int charToIntOne, charToIntTwo, i;
bool carryOver = false;
std::string binStore = "";
//find out how much of each array is populated
int arrOnePop = 0, arrTwoPop = 0;
while (binOne[arrOnePop] != '\0' || binTwo[arrTwoPop] != '\0' && arrOnePop < 255)
{
if (binOne[arrOnePop] == '1' || binOne[arrOnePop] == '0')
arrOnePop++;
if (binTwo[arrTwoPop] == '1' || binTwo[arrTwoPop] == '0')
arrTwoPop++;
if (binOne[arrOnePop] == '\0' && binTwo[arrTwoPop] != '\0')
{
arrOnePop++;
binOne[arrOnePop] = '0';
binOne[arrOnePop + 1] = '\0';
}
if (binTwo[arrTwoPop] == '\0' && binOne[arrOnePop] != '\0')
{
arrTwoPop++;
binTwo[arrTwoPop] = '0';
binTwo[arrTwoPop + 1] = '\0';
}
}
//since both arrays are populated to be the same size, add the binary numbers right to left
for (i = (arrTwoPop - 1); i >= 0; i--)
{
charToIntOne = binOne[i] - '0';
charToIntTwo = binTwo[i] - '0';
if (carryOver == true && (charToIntOne + charToIntTwo) >= 1)
{
binStore += "0";
}
else if (carryOver == true && (charToIntOne + charToIntTwo) == 0)
{
binStore += "1";
carryOver = false;
}
else
{
if ((charToIntOne + charToIntTwo) > 1)
{
binStore += "0";
carryOver = true;
}
else if ((charToIntOne + charToIntTwo) == 1)
{
binStore += "1";
carryOver = false;
}
else
{
binStore += "0";
carryOver = false;
}
}
}
//in the event that there was one last carry over, add it to string
if (carryOver == true)
{
binStore += "1";
}
//convert binary storage string to a char array
for (int j = 0; j < binStore.size(); j++)
{
final[binStore.size() - j] = binStore.at(j);
}
return;
}
I'm pretty sure it will be in the addBinaries() function, but i'm not too sure. Maybe it's something I'm missing when adding the binary arrays.
Thank you for any help you can give, and if you have any questions, please ask.