C# program to convert a binary number into a decimal number

Here, we are going to learn how to convert a binary number into a decimal number in C#?
Submitted by Nidhi, on September 12, 2020

Here we will read a binary number and then convert it into a corresponding decimal number.

Program:

The source code to convert a binary number to a decimal number is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

//C# program to convert a binary number into a decimal number.

using System;

class Program
{
    static void Main(string[] args)
    {
        int binNum      = 0;
        int decNum      = 0;
        int i           = 0;
        int rem         = 0; 
        
        Console.Write("Enter a binary number: ");
        binNum = int.Parse(Console.ReadLine()); 
        

        while (binNum > 0)
        {
            rem = binNum % 10;
            decNum = decNum + rem * (int)Math.Pow(2, i);
            binNum = binNum / 10;
            i++;
        }
        Console.WriteLine("\nDecimal number: " + decNum);
    }
}

Output:

Enter a binary number: 0111

Decimal number: 7
Press any key to continue . . .

Explanation:

In the above program, we create a class Program that contains the Main() method, In the Main() method we read a binary number from user input and then convert the binary number into a corresponding decimal number.

Her we took input number 0111 then the expression for conversion will be:

=0*23 + 1*22+1*21+1*20
=0+4+2+1
=7
while (binNum > 0)
{
    rem = binNum % 10;
    decNum = decNum + rem * (int)Math.Pow(2, i);
    binNum = binNum / 10;
    i++;
}

In the above code, we find each digit of the given number by getting the remainder after dividing 10 and then divide the number until it becomes zero. Then generate an expression for the conversion and store the result into variable decNum and then print the value of variable decNum on the console screen.






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.