Binary addition of 2 values represented as strings

我们两清 提交于 2019-12-08 19:34:15

问题


I have two strings:

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 perform binary addition between the two so the answer will be 00011 ( 3).


回答1:


System.Convert should be able to do the work for you

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

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

(you may have to tune the strings a bit)




回答2:


You do it just as you would do it on paper. Start from right and move left. if A[i] + B[i] + carry >= 2, carry remains 1 and you move on. Otherwise, write A[i] + B[i] + carry and set carry 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

And so on.




回答3:


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



回答4:


I would recommend parsing the data to ints and then adding them, then outputing the result as binary.




回答5:


Very easy -- write a lookup table for 'addition' of binary characters, don't forget to carry if necessary, and send me 50% of the credit you get for the work.




回答6:


var sum = Convert.ToString(Convert.ToInt32("00010", 2) + Convert.ToInt32("00001", 2), 2).PadLeft(5, '0');

"00011"

PadLeft is not really needed, but if the strings had different length you would get a the same format. Example:

var sum = Convert.ToString(Convert.ToInt32("0000010", 2) + Convert.ToInt32("001", 2), 2).PadLeft(5, '0');

"00011"



来源:https://stackoverflow.com/questions/2252806/binary-addition-of-2-values-represented-as-strings

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!