HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Binary addition with strings

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
withadditionbinarystrings

Problem

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 = 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.

Solution

strings of any length as binary numbers

Why are they strings? Something like bool[] would fit much better and it would also make your code simpler.

string a, string b


Those are not very good names. maybe use something like left and right or first and second?

In production code, you should verify that parameters fit your requirements (in your case, that the string contains only '0's and '1's) and throw an exception otherwise.

if (a.Length < b.Length)
{
    string c = a;
    a = b;
    b = c;
}


A simpler way to write this would be to use recursion:

if (a.Length < b.Length)
{
    return BinAdd(b, a);
}


bool addLeft = false;


A better name for this variable would be carry.

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);


All this logic could be simplified by a lot by using a variable to count the ones (including carry). Something like (not tested):

int sum = 0;

if (j >= 0 && b[j] == '1')
    sum++;

if (a[i] == '1')
    sum++;

if (addLeft)
    sum++;

sb.Append(sum % 2);

addLeft = sum / 2 == 1;


char[] cx = new char[sb.Length];
sb.CopyTo(0, cx, 0, sb.Length);
Array.Reverse(cx);

return new string(cx);


Instead of this, you could start with List instead of StringBuilder, Reverse() that and then create a string out of it (possibly using string.Join(null, digits), assuming you name the list digits).

Code Snippets

string a, string b
if (a.Length < b.Length)
{
    string c = a;
    a = b;
    b = c;
}
if (a.Length < b.Length)
{
    return BinAdd(b, a);
}
bool addLeft = false;
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);

Context

StackExchange Code Review Q#57452, answer score: 2

Revisions (0)

No revisions yet.