Search code examples
c#binaryaddition

Binary addition of 2 values represented as strings


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


Solution

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