Q:

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

belongs to collection: C# Basic Programs | basics

0

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

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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.

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C# Basic Programs | basics

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
C# program to convert a temperature from Fahrenhei... >>
<< C# program to convert a decimal number into a bina...