Binary addition of 2 values ​​represented as strings

I have two lines:

string a = "00001"; /* which is decimal 1 I've converted with next string:
string a = Convert.ToString(2, 2).PadLeft(5, '0'); */
string b = "00010";

I want to do binary addition between the two, so the answer is 00011 (3).

+5
source share
5 answers

System.Convert should be able to do your job

int number_one = Convert.ToInt32(a, 2);
int number_two = Convert.ToInt32(b, 2);

return Convert.ToString(number_one + number_two, 2);

(you may need to tweak the strings a bit)

+12
source

You do it the same way you do on paper. Start right and move left. if A [i] + B [i] + carry> = 2, the transfer remains 1 and you move on. Otherwise, write A [i] + B [i] + hyphenation and set the hyphenation to 0.

a = "00001"; b = "00010";

carry = 0; a [4] + b [4] + carry = 1, write 1, set carry = 0: 00001

a [3] + b [3] + carry = 1, write 1, set carry = 0: 00011

.

+3

Very simple - write a search table to "add" binary characters, do not forget to bear it if necessary, and send me the 50% loan that you get for the work.

0
source

I would recommend parsing the data in int and then adding it, and then outputting the result as binary.

0
source
private static bool[] BinaryAdd(bool[] originalbits, long valuetoadd)
    {
        bool[] returnbits = new bool[originalbits.Length];

        for (long i = 0; i <= valuetoadd - 1; i++)
        {
            bool r = false; //r=0
            for (long j=originalbits.Length-1;j<=originalbits.Length;j--)
            {
                bool breakcond = false;
                bool o1 = originalbits[j];
                if (r == false)
                {
                    if (o1 == false) { o1 = true; breakcond = true; }//break
                    else if (o1 == true) { o1 = false; r = true; }
                }
                else
                {
                    if (o1 == false) { o1 = true; breakcond = true; }//break
                    else if (o1 == true) { o1 = false; r = true; }
                }

                originalbits[j] = o1;
                if (breakcond == true)
                {
                    break;
                }
            }

        }
        returnbits = originalbits;

        return returnbits;
    }
0
source

All Articles