The following method will add two strings of any length as binary numbers assuming the characters 1
and 0
. I made this for fun in my spare time. Improvements are not critical but I would like to hear them. I would also like to know if there is a more efficient algorithm to simulate a ALU.
static string BinAdd(string a, string b)
{
if (a.Length < b.Length)
{
string c = a;
a = b;
b = c;
}
StringBuilder sb = new StringBuilder(a.Length);
bool addLeft = false;
for (int i = a.Length - 1, j = b.Length - 1; i >= 0; i--, j--)
{
char c = '1';
bool add = addLeft;
addLeft = false;
if (j >= 0)
{
if (a[i] == '1' && b[j] == '1')
{
c = '0';
addLeft = true;
}
else if (a[i] == '0' && b[j] == '0')
{
c = '0';
}
else if (add)
{
addLeft = true;
}
}
else
{
if (a[i] == '0')
{
c = '0';
}
else if (add)
{
addLeft = true;
}
}
sb.Append(add ? (c == '1' ? '0' : '1') : c);
}
if (addLeft)
{
sb.Append('1');
}
char[] cx = new char[sb.Length];
sb.CopyTo(0, cx, 0, sb.Length);
Array.Reverse(cx);
return new string(cx);
}
I'm aware that no validation is done, but I didn't intend to.