Users Online

· Guests Online: 146

· Members Online: 0

· Total Members: 188
· Newest Member: meenachowdary055

Forum Threads

Newest Threads
No Threads created
Hottest Threads
No Threads created

Latest Articles

C# Program to Convert Binary to Decimal

C# Program to Convert Binary to Decimal

 

 

This is a C# Program to perform binary to decimal conversion.

Problem Description

This C# Program Performs Binary to Decimal Conversion.

Problem Solution

This C# Program converts the given binary number into decimal. The program reads the binary number, does a modulo operation to get the remainder, multiples the total by base 2 and adds the modulo and repeats the steps.

Program/Source Code

Here is source code of the C# Program to Perform Binary to Decimal Conversion.The C# program is successfully compiled and executed with Microsoft Visual Studio.The program output is also shown below.

/*
 * C# Program to Perform Binary to Decimal Conversion
 */
using System;
using System.Collections.Generic;
using System.Text;
 
namespace Program
{
    class Program
    {
        static void Main(string[] args)
        {
            int num, binary_val, decimal_val = 0, base_val = 1, rem;
            Console.Write("Enter a Binary Number(1s and 0s) : ");
            num = int.Parse(Console.ReadLine()); /* maximum five digits */
            binary_val = num;
            while (num > 0)
            {
                rem = num % 10;
                decimal_val = decimal_val + rem * base_val;
                num = num / 10 ;
                base_val = base_val * 2;
            }
            Console.Write("The Binary Number is : "+binary_val);
            Console.Write("\nIts Decimal Equivalent is : "+decimal_val);
            Console.ReadLine();
        }
    }
}
Program Explanation

In this C# program we are reading a binary number using ‘num’ variable. While loop is used to check the value of ‘num’ variable is greater than 0. If the condition is true then execute the iteration of the loop.

 

Compute the modulus of the value of ‘num’ variable by 10 and assign the value to ‘rem’ variable. Multiply the value with the value of ‘baseval’ variable. Add the resulted value with the value of ‘decimal_val’ variable.

Divide the value of ‘num’ variable by 10. Multiply the value of ‘base_val’ variable with 2 and assign the value to base_val variable. Print the decimal value of a binary number.

Runtime Test Cases
 
Enter a Binary Number(1s and 0s) : 101010
The Binary Number is : 101010
Its Decimal Equivalent is : 42

Comments

No Comments have been Posted.

Post Comment

Please Login to Post a Comment.

Ratings

Rating is available to Members only.

Please login or register to vote.

No Ratings have been Posted.
Render time: 0.87 seconds
10,810,719 unique visits