## C# || How To Add Two Binary Strings Using C#

The following is a module with functions which demonstrates how to add two binary strings together using C#.

1. Add Binary – Problem Statement

Given two binary strings **a** and **b**, return their sum as a binary string.

**Example 1:**

Input: a = "11", b = "1"

Output: "100"

**Example 2:**

Input: a = "1010", b = "1011"

Output: "10101"

2. Add Binary – Solution

The following is a solution which demonstrates how to add two binary strings together.

In this solution, we start at the end of both strings, and perform basic math on each number, adding them together. If any mathematical carry over is required, that is added to the next loop iteration.

```
```
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
// ============================================================================// Author: Kenneth Perkins// Date: Oct 13, 2021// Taken From: http://programmingnotes.org/// File: Solution.cs// Description: Demonstrates how to add two binary strings together// ============================================================================public class Solution { public string AddBinary(string a, string b) { // Process numbers starting from the end var aLength = a.Length - 1; var bLength = b.Length - 1; // Go through data and add each number together var stack = new Stack<int>(); var carry = 0; while (aLength >= 0 || bLength >= 0) { var aValue = 0; var bValue = 0; if (aLength >= 0) { aValue = CharToInt(a[aLength--]); } if (bLength >= 0) { bValue = CharToInt(b[bLength--]); } // Add the a and b values together, including carry var sum = carry + aValue + bValue; // Determine the carry over value carry = sum / 2; // Save the digit var digit = sum % 2; stack.Push(digit); } // Add any data left over if (carry > 0) { stack.Push(carry); } // Save results var result = new StringBuilder(); while (stack.Count > 0) { result.Append(stack.Peek()); stack.Pop(); } return result.ToString(); } private int CharToInt(char ch) { return ch - '0'; }}// http://programmingnotes.org/

**QUICK NOTES**:

The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

Once compiled, you should get this as your output for the example cases:

"100"

"10101"

## Leave a Reply