Hi there,
I tried binary addition. It seems to work fine. Could someone tell me if there's a better way of doin this or any bugs that could be uncovered in the code below?
I appreciate your time.
Thanks,
Tina
#include <stdio.h>
void binaryAdd(char *, char *);
int main()
{
char op1[20], op2[20];
char sum[20];
char *p, *p1;
fgets(op1, sizeof(op1), stdin);
fgets(op2, sizeof(op2), stdin);
if( (p = strchr(op1, '\n')) != NULL)
*p = '\0';
if( (p1 = strchr(op2, '\n')) != NULL)
*p1 = '\0';
binaryAdd(op1, op2);
return 0;
}
void binaryAdd(char *first, char *second)
{
int carry = 0;
int flen = strlen(first);
int slen = strlen(second);
char *tfirst = first + strlen(first) - 1;
char *tsecond = second + strlen(second) - 1;
int *result = malloc(sizeof(int) * 16);
int *temp = result;
for(; flen > 0 || slen > 0; flen--, slen--)
{
if((*tfirst - '0') ^ (*tsecond - '0'))
{
if(!carry)
{
*temp++ = 1 + carry;
carry = 0;
}
else
*temp++ = 0;
}
else
{
if((*tfirst - '0') & (*tsecond -'0'))
{
*temp++ = (0 + carry);
carry = 1;
}
else
{
*temp++ = (0 + carry);
carry = 0;
}
}
tfirst--;
tsecond--;
}
if (carry == 1)
{
*temp++ = carry;
}
while(temp-- != result)
printf("%d", *temp);
free(result);
}