C# - Sum of Two Binary Numbers

Here, we are going to learn how to calculate the sum of two binary numbers in C#? By Nidhi Last updated : April 15, 2023

Addition of Binary Numbers

Here we will calculate the sum of two given binary numbers. As we know that a binary number is represented using only two digits 0 and 1.

C# program to calculate the sum of two binary numbers

The source code to calculate the sum of two binary numbers is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

//C# program to calculate the sum of binary numbers.

using System;
class BinarySum
{
    static void CalculateBinarySum(int num1, int num2)
    {
        int i   = 0;
        int rem = 0;
        string str="";

        while (num1 != 0 || num2 != 0)
        {
            str += (num1 % 10 + num2 % 10 + rem) % 2;
            rem = (num1 % 10 + num2 % 10 + rem) / 2;

            num1 = num1 / 10;
            num2 = num2 / 10;
        }

        if (rem != 0)
            str += rem;
        

        Console.Write("Sum is : ");
        for (i = str.Length - 1; i >= 0; i--)
        {
            Console.Write(str[i]);
        }
        Console.WriteLine();
    }
    public static void Main()
    {
        int num1=0;
        int num2=0;
        
        Console.Write("Enter 1st binary number: ");
        num1 = Convert.ToInt32(Console.ReadLine());
        
        Console.Write("Enter 2nd binary number: ");
        num2 = Convert.ToInt32(Console.ReadLine());

        CalculateBinarySum(num1, num2);
    }
}

Output

Enter 1st binary number: 1010
Enter 2nd binary number: 1101
Sum is : 10111
Press any key to continue . . .

Explanation

Here, we created a class BinarySum that contains two static methods CalculateBinarySum() and Main().

In the CalculateBinarySum() method we took num1 and num2 as an argument and then add each digit according to the rules of binary addition and then we concatenate the result into the string and we print the resulted string in the reverse direction to print actual output on the console screen.

The Main() method is the entry point for the program, here we read the value num1 and num2 from the user and passed the values to the CalculatBinarySum() method to calculate and print the binary addition on the console screen.

C# Basic Programs »


Related Programs




Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.