I'm working on a program to add two binary numbers together from command line inputs (argv, argc). It is also left justified.
For example: $a.out 0 1 returns 1, $a.out 10 1 returns 11 etc.
I'm using a function to do the addition and I know 100% my issue lies within my function, but I cant figure out what I'm doing wrong. When I add two binary numbers that have a carry of '0' at the very from it doesn't print the '1' in the sum. I have another issue where some sums are printed in reverse but not others. If anyone could point me in the right directions on what I'm doing wrong, I'd greatly appreciate it.
Examples of the sums that are wrong:
$a.out 10 10
00 // should be "100"
$a.out 11 11
01 // should be "110"
$a.out 100 100
000 // should be "1000"
$a.out 110000 1
100011 // should be "110001"
My function:
bool add (const char aug[], const char add[], char sum[])
//aug is the first command line binary number (argv[1]), add is the second (argv[2])
{
char carry = '0';
int ag = strlen(augend) - 1;
int ad = strlen(addend) - 1;
int max = ((ag > ad)? ag : ad);
for (int i = 0; i <= max; ag--, ad--, i++)
{
char augDigit = (ag < 0)? '0' : augend[ag];
char addDigit = (ad < 0)? '0' : addend[ad];
switch (augDigit + addDigit + carry)
{
case '0' + '0' + '0':
sum[i] = '0';
carry = '0';
break;
case '1' + '0' + '0':
sum[i] = '1';
carry = '0';
break;
case '1' + '1' + '0':
sum[i] = '0';
carry = '1';
break;
case '1' + '1' + '1':
sum[i] = '1';
carry = '1';
break;
}
}
return true;
// returns true if the sum is less than 36 digits but I'll deal with
// that once i fix this issue
}