C Sharp to convert a binary number into a decimal number using math function

QuestionsCategory: C#C Sharp to convert a binary number into a decimal number using math function
Pooja PatelPooja Patel asked 1 year ago

Write a program in C Sharp to convert a binary number into a decimal number using math function

1 Answers
Mahesh DeshmaneMahesh Deshmane answered 1 year ago

C# Console program to convert Binary number to Decimal:

Read more about Binray Number base-2
Using Math metical Approach:
Extract the digits of the given binary number starting from rightmost digits using the modulus operator. then multiply the digit with the proper base i.e. power of 2 and add the result into the decimal variable. The final result will be in the decimal variable.

using System;

namespace Conversion
{
    class Program
    {
        static void Main()
        {
            Console.WriteLine("Enter Binary Number:");
            var binaryNumber = Convert.ToInt32(Console.ReadLine());
            var decimalValue = 0;
            var base1 = 1;

            while (binaryNumber > 0)
            {
                var reminder = binaryNumber % 10;
                binaryNumber /= 10;
                decimalValue += reminder * base1;
                base1 *= 2;
            }
            Console.Write($"Converted Decimal Value: {decimalValue}");
            Console.ReadLine();
        }
    }
}


C# inbuild conversion method approach:

using System;

namespace Conversion
{
    class Program
    {
        static void Main()
        {
            Console.WriteLine("Enter Binary Number:");
            var binaryNumber = Console.ReadLine();
            var decimalValue = Convert.ToInt32(binaryNumber, 2);
            Console.WriteLine($"Decimal Value : {decimalValue} ");
            Console.ReadLine();
        }
    }
}