How To Convert Binary To Number In C#

Computers carry out their operations or communicate with other resources through binary language. Binary language is the basic language of digital devices which includes 0 and 1 to communicate with other resources. Binary language is not recommended for standard numeric formats.

Decimal is the standard format for the display of numerical or number data types. Decimal consists of 0-9 numerical. Decimal is recommended for the daily life data display. Hence, it is necessary to convert binary to decimal for an efficient user experience.

Here, we will emphasize on “How to convert binary to number in C#”.

Why Is There A Need To Convert  Binary To Number In C#?

Let us discuss the real-life need for conversion for programmers. What can be scenarios in which programmers need to convert binary data into numbers?

  1. Decimal output – If the output of the query is decimal instead of binary or the user requests decimal data, then programmers have to convert binary data into decimal.
  2. Standard data display – Most of the time, the display of the query results or data display is to be done in the standard format. This standard format can be achieved through only decimal format.

Hope this help you to understand – “ how to change binary to number in C# ”.

Different Approaches To Convert Binary To Number In C#

Converting binary data to numbers can be an essential task for the programmer to develop the application. This conversion can be achieved by different approaches in C# programming language. They are listed below.

  1. Using Convert.ToInt32 method
  2. Using custom algorithm
  3. Using LINQ class
  4. Using the bitwise left shift operator
  5. Using BigInteger class

All these five approaches are effective for the conversion. We will discuss them in detail by code and explanation in the upcoming sections. Programmers who want to excel in this conversion should practice the code to get a better understanding of the topic.

Approach 1: Using Convert.ToInt32 method

The Convert.ToInt32 method is the predefined method in C# programming language to convert the binary data into decimals or numbers. This method is very effective and beginner friendly as it is simple to apply in any application development.

Solution Code:-

using System;

// declare the public class
public class HelloWorld
{
    public static void Main(string[] args)
    {
        // take the user input
        Console.Write("Enter a binary number: ");
        string binaryInput = Console.ReadLine();
        
        // use the method for the conversion
        int decimalOutput = Convert.ToInt32(binaryInput, 2);
        
        // display the output on the console
        Console.WriteLine("Decimal equivalent: " + decimalOutput);
    }
}

Output:-

Enter a binary number: 1010
Decimal equivalent: 10

Explanation:-

  1. Create a public class for the execution of code.
  2. Take the user input using the write method and read all the binary numbers from it.
  3. Use the Convert.ToInt32 method to convert the binary numbers into number
  4. The Convert.ToInt32 method takes two inputs.  First is the binary variable and another one is the digit – 2.
  5. Then, print the final result on the console.

Approach 2: Using custom algorithm

In this algorithm, we will take the binary data from the user and then traverse the data using a for loop. We will use a traditional mathematical calculation to convert the data. In traditional mathematics, each binary digit is added by multiplying each unit with the base of 2.

Solution Code:-

using System;

// declare the public class
public class HelloWorld
{
    public static void Main(string[] args)
    {
        // take the user input
        Console.Write("Enter a binary number: ");
        string binaryInput = Console.ReadLine();
        
        // declare the decimal and basevalue
        int decimalOutput = 0;
        int baseValue = 1;
        
        // create a loop to traverse all the binary data and use the method to carry out the conversion
        for (int i = binaryInput.Length - 1; i >= 0; i--)
        {
            if (binaryInput[i] == '1')
            {
                decimalOutput += baseValue;
            }
            baseValue *= 2;
        }

        // display the output on the console
        Console.WriteLine("Decimal equivalent: " + decimalOutput);
    }
}

Output:-

Enter a binary number: 1010010
Decimal equivalent: 82

Explanation :

  1. Create a public class for the execution of code.
  2. Take the user input using the write method and read all the binary numbers from it.
  3. Create two variables to declare the Decimal value and base value for the loop traverse
  4. Use for loop to traverse all the binary data as the method is capable to convert only one binary number at a time.
  5. Use the custom algorithm to convert the binary numbers into number
  6. Save the resulting values in a decimal variable.
  7. Then, print the final result on the console.

Approach 3: Using LINQ

The LINQ library is the extension of C# programming to convert and use mathematical expressions. To achieve the conversion, we will use this library by using Math.Pow() method.

Solution Code:-

using System;
using System.Linq;

public class HelloWorld
{
    public static void Main(string[] args)
    {
        // take the user input
        Console.WriteLine("Enter a binary number: ");
        string binaryInput = Console.ReadLine();
        
        // declare the decimal variable and use the method for the conversion
        int decimalOutput = binaryInput
            .Reverse()
            .Select((c, i) => c == '1' ? (int)Math.Pow(2, i) : 0)
            .Sum();
        
        // display the output on the console
        Console.WriteLine("Decimal equivalent: " + decimalOutput);
    }
}

Output:-

Enter a binary number: 10111

Decimal equivalent: 7

Explanation :

  1. Create a public class for the execution of code.
  2. Take the user input using the write method and read all the binary numbers from it.
  3. Create a decimal variable and use the LINQ method for the conversion.
  4. Then, print the final result on the console.

Approach 4: Using the bitwise left shift operator

The bitwise left shift operator is another method for the conversion. Programmers have to use the loop method to traverse all the binary data. Then, we use the bitwise left shift operator to store the decimal data in the variable.

Solution Code:-

using System;

public class HelloWorld
{
    public static void Main(string[] args)
    {
        // take the user input
        Console.Write("Enter a binary number: ");
        string binaryInput = Console.ReadLine();
        
        // declare the decimal variable to store the decimal output
        int decimalOutput = 0;
        
        // create a loop to traverse the binary data
        for (int i = binaryInput.Length - 1, j = 0; i >= 0; i--, j++)
        {
            int binaryDigit = binaryInput[i] - '0';
            
            // use the bit-wise operator 
            decimalOutput += binaryDigit << j;
        }
        
        // display the output on the console
        Console.WriteLine("Decimal equivalent: " + decimalOutput);
    }
}

Output:-

Enter a binary number: 111000
Decimal equivalent: 56

Explanation :

  1. Create a public class for the execution of code.
  2. Take the user input using the write method and read all the binary numbers from it.
  3. Create a decimal variable and use the for loop and bitwise left shift operator method for the conversion.
  4. Then, print the final result on the console.

Approach 5: Using BigInteger class

This class has the BigInteger method to convert binary data into decimals or numbers. This method has the pre-defined syntax in the BigInteger class.

But, it requires external resources. Also, this method is not applicable to online compilers as they miss the external dependencies.

Sample code :

using System;
using System.Numerics;

public class HelloWorld
{
    public static void Main(string[] args)
    {
        // take the user input
        Console.Write("Enter a binary number: ");
        string binaryInput = Console.ReadLine();
        
        // declare the variable to store the decimal value
        int decimalOutput = 0;
        
        // create a loop to traverse the binary data
        for (int i = binaryInput.Length - 1, j = 0; i >= 0; i--, j++)
        {
            int binaryDigit = binaryInput[i] - '0';
            
            // use the method
            decimalOutput += binaryDigit * BigInteger.Pow(2, j);
        }
        
        // display the output on the console
        Console.WriteLine("Decimal equivalent: " + decimalOutput);
    }
}

Output :

Enter a binary number: 1101010011010
Decimal equivalent: 6810

Explanation :

  1. Create a public class for the execution of code.
  2. Take the user input using the write method and read all the binary numbers from it.
  3. Create a decimal variable and use the for loop and BigInteger class method for the conversion.
  4. Then, print the final result on the console.

All the above approaches will you to understand “ How to convert binary to number in C# ”.

Best Approach for Converting Binary to Number in C#

The Convert.ToInt32 method is the best approach according to our experience. Let us discuss some points to prove the statement.

  1. Easy to use – This method is more reliable and easy to use as it has a simple syntax. The syntax can be applied to any programming file which deals with binary data.
  2. Beginner friendly – The Convert.ToInt32 method doesn’t involve any advanced concept of programming and has predefined syntax. As it is easy to use, it becomes more beginner friendly.
  3. No external dependency – The Convert.ToInt32 method doesn’t require any external dependency like an external class or library while the implementation.

Sample Problems

Sample problem 1:

Apply the method binary to a number in the application development of the cashier software of the grocery super shop. The cost of the item should be printed on the bill. Cost of the item is stored in the binary form in the database, convert it into number and print it on the bill.

Sample problem 2:

Apply the method binary to a number in the application development of the health report generator software of the hospital. The weight of the patient should be printed on the health report. The weight of the patient is stored in binary form in the database, convert weight into number and print it on the health report.

Solution :

  1. Create a public class for the execution of code.
  2. Get the weight of the patient from the database and read all the binary numbers from it.
  3. Create two variables to declare the Decimal value and base value for the loop traverse
  4. Use for loop to traverse all the binary data as the method is capable to convert only one binary number at a time.
  5. Use the custom algorithm to convert the binary numbers into number
  6. Save the resulting values in a decimal variable.
  7. Then, print the final result or the weight of the patient on the console or health report.

Code :

using System;

// declare the public class
public class HelloWorld
{
    public static void Main(string[] args)
    {
        // get the weight of the patient from the database
        string binaryInput = "110110";
        
        // declare the decimal and basevalue
        int decimalOutput = 0;
        int baseValue = 1;
        
        // create a loop to traverse all the binary data and use the method to carry out the conversion
        for (int i = binaryInput.Length - 1; i >= 0; i--)
        {
            if (binaryInput[i] == '1')
            {
                decimalOutput += baseValue;
            }
            baseValue *= 2;
        }

        // display the output or weight on the health report or on the console
        Console.WriteLine("The weight of the patient is: " + decimalOutput);
    }
}

Output :

The weight of the patient is: 54

Sample problem 3:

Apply the binary to a number approach in the application development of the final result generation software of the school. The height of the student should be printed on the mark sheet. The height of the student is stored in binary form in the database, convert the data into a number, and print on the mark sheet.

Solution :

Code :

using System;
using System.Linq;

public class HelloWorld
{
    public static void Main(string[] args)
    {
        // Get the height of the student from the database
        string binaryInput = "1001010";
        
        // declare the decimal variable and use the method for the conversion
        int decimalOutput = binaryInput
            .Reverse()
            .Select((c, i) => c == '1' ? (int)Math.Pow(2, i) : 0)
            .Sum();
        
        // display the height of the student on the console or on the marksheet
        Console.WriteLine("The height of the student is " + decimalOutput + “ cm”);
    }
}

Output :

The height of the student is 74 cm

Sample problem 4:

Apply the binary to a number approach in the application development of the merit list generation software of the college. The percentage of the candidate should be printed on the merit list. The percentage of the candidate is stored in binary form in the database, convert the data into a number, and print on the merit list.

Solution :

  1. Create a public class for the execution of code.
  2. Get the percentage of the candidate and read all the binary numbers from it.
  3. Create a decimal variable and use the for loop and bitwise left shift operator method for the conversion.
  4. Then, print the final result on the console or the percentage of the student on the merit list.

Code :

using System;

public class HelloWorld
{
    public static void Main(string[] args)
    {
        // get the percentage of the candidate from the database
        string binaryInput = "1010100";
        
        // declare the decimal variable to store the decimal output
        int decimalOutput = 0;
        
        // create a loop to traverse the binary data
        for (int i = binaryInput.Length - 1, j = 0; i >= 0; i--, j++)
        {
            int binaryDigit = binaryInput[i] - '0';
            
            // use the bit-wise operator 
            decimalOutput += binaryDigit << j;
        }
        
        // display the output on the console or percentage on the merit list
        Console.WriteLine("The percentage of the candidate: " + decimalOutput);
    }
}

Output :

The percentage of the candidate: 84

Sample problem 5:

Apply the binary to a number approach in the application development of the reservation software of the railways. The age of the passenger should be printed on the reservation chart. The age of the passenger is stored in binary form in the database, convert the data into a number, and print on the reservation chart.

Solution :

  1. Create a public class for the execution of code.
  2. Get the age of the passenger from the database and read all the binary numbers from it.
  3. Create a decimal variable and use the for loop and BigInteger class method for the conversion.
  4. Then, print the final result on the console or the age of the passenger on the reservation chart.

Code :

using System;
using System.Numerics;

public class HelloWorld
{
    public static void Main(string[] args)
    {
        // get the age of the passenger fromm the database
        string binaryInput = "101000";
        
        // declare the variable to store the decimal value
        int decimalOutput = 0;
        
        // create a loop to traverse the binary data
        for (int i = binaryInput.Length - 1, j = 0; i >= 0; i--, j++)
        {
            int binaryDigit = binaryInput[i] - '0';
            
            // use the method
            decimalOutput += binaryDigit * BigInteger.Pow(2, j);
        }
        
        // display the output on the console or the age of the passenger on the reservation chart
        Console.WriteLine("The age of the passenger is: " + decimalOutput + “ years old”);
    }
}

Output :

The age of the passenger is 40 years old

Conclusion

The conversion of the binary data into numbers is an essential task for a programmer if he or she has to retrieve the data from the storage of the device.

This conversion can be achieved through the different approaches which are explained well with the help of code, its explanation, and detailed description.

Also, we have declared the Convert.ToInt32 method is the best approach for conversion as it is easy to use in application development.