why so complicated? all you really need is "strtol()" and the addition operator.
int binaryAdd(char *first, char *second, int *sum)
{
int val1, val2;
char *ptr1, *ptr2;
size_t length;
val1 = strtol(first,&ptr1,2);
val2 = strtol(second,&ptr2,2);
if (ptr1 == first || ptr2 == second)
{
printf("\ninvalid entry.\n\n");
return 0;
}
length = ptr1-first;
if ((ptr2-second) > length)
length = ptr2-second;
*sum = val1+val2;
printf("\n %*s (%d)\n+ %*s (%d)\n\n= %*s (%d)\n\n",
length, first, val1, length, second, val2, length, " ", *sum);
return 1;
}
(The rest is just decoration)
I'll leave conversion of the numeric sum, back into a binary string, as an exercise to the reader :P
.
jephthah
Posting Maven
2,592 posts since Feb 2008
Reputation Points: 2,143
Solved Threads: 179
Skill Endorsements: 5
at the "bit level", every integer is inherently binary and hex and decimal... it does not matter, because there's only a difference when you print it.
so, you can make it hard if you like, just for the sake of having a challenge or if your instructor requires you to do so for learning purposes.
but if you're not required to make it difficult, i'd say use the <stdlib.h> standard library functions whenever possible.
jephthah
Posting Maven
2,592 posts since Feb 2008
Reputation Points: 2,143
Solved Threads: 179
Skill Endorsements: 5