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#? By Nidhi Last updated : April 15, 2023

Binary to Decimal Conversion in C#

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

C# program for binary to decimal conversion

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.

C# Basic Programs »


Related Programs



Comments and Discussions!

Load comments ↻





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