Add two binary numbers in C#

class AddTwoBinaryStrings
{
static void Main(string[] args)
{
ConsoleKeyInfo keyPress;
do
{
Console.WriteLine(“Enter two binary strings:”);
string b1 = Console.ReadLine();
string b2 = Console.ReadLine();
string sum = string.Empty;
int carry = 0, b1Length = b1.Length – 1, b2Length = b2.Length – 1;

while (b1Length >= 0 || b2Length >= 0)
{
if (b1Length >= 0)
{
carry += b1[b1Length] – ‘0’;
}
if (b2Length >= 0)
{
carry += b2[b2Length] – ‘0’;
}

if (carry == 3)
{
sum = “1” + sum;
carry = 1;
}
else if (carry == 2)
{
sum = “0” + sum;
carry = 1;
}
else
{
sum = carry.ToString() + sum;
carry = 0;
}
–b1Length;
–b2Length;
}
if (carry > 0)
{
sum = “1” + sum;
}

Console.WriteLine(sum);
keyPress = Console.ReadKey();
} while (keyPress.Key != ConsoleKey.Escape);
}
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s