Binary To Decimal Conversion in C#

Introduction

In this article, we will explore methods to convert binary numbers to decimal numbers using C#.

We will explore,

  1. What is Decimal Number
  2. What is a Binary Number
  3. Convert Binary Number to Decimal Number

Below are a few examples of inputs and Outputs.

Examples

  • Input: 100 (Binary Number)
  • Output: 4 (Decimal Number)
  • Input: 1001 (Binary Number)
  • Output: 9 (Decimal Number)

This is an essential technical interview question that may be posed to beginner, intermediate, and experienced candidates.

We will build this program using two different methods.

We previously covered the following.

  1. How to Reverse Number in C#
  2. How to Reverse a String in C#
  3. Palindrome String Program in C#
  4. Palindrome Number in C#
  5. How to Reverse Order of the Given String
  6. How To Reverse Each Word Of Given String
  7. How To Remove Duplicate Characters From String In C#
  8. Bubble Sort Algorithm
  9. Decimal to Binary Conversion in C# 

What are Decimal Numbers?

The numeral with a base of 10 is referred to as decimal Numbers. That means decimal numbers range from 0 to 9.

Example

  • 4
  • 71

What are Binary Numbers?

The Binary numbers are those numbers for which the base is 2. This implies that the binary numbers can be represented using just two digits, namely 0 and 1.

Example

  • 101
  • 111111
  • 10101

Convert Binary Number to Domical Number

Method 1

var str = Console.ReadLine();
int number = Convert.ToInt32(str);
Console.WriteLine(Convert.ToInt32(number.ToString(), 2));
Console.ReadLine();

Output

Output

Let's try with different inputs.

Inputs

Let's do it with another method.

Method 2

Console.WriteLine("Enter Binary Number");
var str = Console.ReadLine();
int binaryNumber = Convert.ToInt32(str);
int decimalNumber = 0;
int baseNumber = 1;
while (binaryNumber > 0)
{
    int reminder = binaryNumber % 10;
    binaryNumber = binaryNumber / 10;
    decimalNumber = decimalNumber + reminder * baseNumber;
    baseNumber = baseNumber * 2;
}
Console.WriteLine($"Decimal Number: {decimalNumber}");
Console.ReadLine();

Let's execute the program and observe the result.

Output

Binary Number

Let's try with different inputs.

Decimal numbers

We have learned two ways to convert binary numbers to decimal numbers. I hope you find this article enjoyable and useful.


Similar Articles