0

I was searching for a solution to adding two binary strings. My test data for proving the addition:

10 + 1 => 11
1001 + 1 => 1010
1101 + 100 => 10001
10101010 + 11001100 => 101110110

This was the code I've found by googling:

public static string AddBinary(string a, string b)
{
    string result = "";

    // Initialize digit sum 
    int s = 0;

    // Traverse both strings starting from last characters 
    int i = a.Length - 1;
    int j = b.Length - 1;

    while (i >= 0 || j >= 0 || s == 1)
    {
        // Compute sum of last digits and carry 
        s += (i >= 0 ? a[i] - '0' : 0); // if i > 0
        s += (j >= 0 ? b[j] - '0' : 0);

        // If current digit sum is 1 or 3, add 1 to result 
        result = (char)(s % 2 + '0') + result;

        // Compute carry 
        s /= 2;

        // Move to next digits 
        i--; 
        j--;
    }
    return result;
}

Could someone please explain to me what these three lines of code are actually doing here?

s+= (i >= 0 ? a[i] - '0' : 0);
s+= (j >= 0 ? b[j] - '0' : 0);

result = (char)(s % 2 + '0') + result;

I've never used a char with a plus/minus operator before and not sure what these lines are achieving.

Footnote - the binary calculation looks to be correct

https://dotnetfiddle.net/Hf0tgx

Rob
  • 6,819
  • 17
  • 71
  • 131
  • It means padding cases, so if there is '1' + '101' it actually will be '**00**1' + '101'. So if index is negative on one of the strings but not the other - it means it is padded with zeros. – eocron Feb 10 '21 at 20:44
  • 1
    @eocron OP seem to be asking about "char with a plus/minus operator " and your comment is about "string with plus operator"... Hopefully [duplicate](https://stackoverflow.com/questions/239103/convert-char-to-int-in-c-sharp) I picked is what OP is looking for. – Alexei Levenkov Feb 10 '21 at 20:53
  • It didnt directly answer it but think I was able to infer enough - essentially the char is ASCII and the plus '0' is adding ASCII values together (let me know if thats wrong). Thanks guys! – Rob Feb 10 '21 at 20:58
  • 1
    your comment seem to be other way... `s` is digit (int 0 / int 1) so `s + '0'` converts it to corresponding char - `(char)(1+'0') = '1'`, `'1'-'0'` converts char back to its numeric value. C question https://stackoverflow.com/questions/628761/convert-a-character-digit-to-the-corresponding-integer-in-c has better explanation. – Alexei Levenkov Feb 10 '21 at 21:10
  • I get you! Thats great, thanks for the pointers Alexei :) – Rob Feb 10 '21 at 21:35

0 Answers0