Introduction
In this article, we will explore methods to convert binary numbers to decimal numbers using C#.
We will explore,
- What is Decimal Number
- What is a Binary Number
- 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.
- How to Reverse Number in C#
- How to Reverse a String in C#
- Palindrome String Program in C#
- Palindrome Number in C#
- How to Reverse Order of the Given String
- How To Reverse Each Word Of Given String
- How To Remove Duplicate Characters From String In C#
- Bubble Sort Algorithm
- 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
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
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
Let's try with different 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
Let's try with different inputs.
We have learned two ways to convert binary numbers to decimal numbers. I hope you find this article enjoyable and useful.