I am getting an incorrect result when adding two binary strings "11" + "11". I am expecting "110" but the answer I am getting is "010". I did add a special case if the carry is still 1.
char *addBinary(char *str1, char *str2)
{
int len1 = strlen(str1); //assume both string lengths are same
char *res = (char *)malloc((len1 + 1) * sizeof(char));
int i, a, b;
int carry = 0;
char result;
for (i = len1 - 1; i >= 0; i--)
{
a = str1[i] - '0';
b = str2[i] - '0';
carry = a + b + carry;
printf("%d %d %d \n", a, b, carry % 2);
result = carry % 2 + '0'; //convert to character
carry = carry / 2;
str1[i] = result; //use the existing string for the result
}
if (carry == 0)
{ //if there is no carry just use the existing string and return
printf("Final without carry %s \n", str1);
return str1;
}
else
{ //there was a carry, so put 1 in the 0th location and copy the string
res[0] = 1;
memcpy(res + 1, str1, sizeof(char) * len1);
printf("Final %s %s %d\n", res, str1,strlen(res));
return res;
}
}
int main()
{
char bin_str1[] = "11";
char bin_str2[] = "11";
printf("%s \n",addBinary(bin_str1, bin_str2));
return 0;
}
len1+2bytes with malloc.res[0] = 1;should beres[0] = '1';loop. Thisfor ( i = len1 - 1 ; i >= 0; i--)where a good compiler should warn you that comparison of unsigned expression>= 0is always true in this/your case. Usei = len -1and put your code inwhile ( i > 0 ){ i-- }It should be treated asUBbecause if is always TRUE you get yourself in an infinite LOOP.