How to convert binary to decimal in C#?

By FoxLearn 11/15/2024 8:25:11 AM   38
To convert a binary number to a decimal number in C#, you can manually process the binary digits, or you can use built-in methods like Convert.ToInt32 for a more straightforward approach.

You can convert a binary number to decimal by extracting its digits from right to left using the modulus operator.

For each extracted digit, we multiply it by the corresponding power of 2 (based on its position) and add the result to a running total. At the end, this total represents the decimal equivalent of the binary number.

For example:

Binary number: 10101

Decimal calculation:

Step 1: 1*2^0 = 1

Step 2: 0*2^1 = 0

Step 3: 1*2^2 = 4

Step 4: 0*2^3 = 0

Step 5: 1*2^4 = 16

Decimal Number = 1 + 0 + 4 + 0 + 16 = 21

How to Binary to Decimal Conversion in C# using Convert.ToInt32()?

The simplest and most efficient way to convert a binary string to a decimal integer is by using Convert.ToInt32().

string binaryNumber = "1101";  // example binary number
int decimalNumber = Convert.ToInt32(binaryNumber, 2);  // convert binary string to decimal in C#

How to implement binary to decimal conversion in C#?

If you'd prefer to convert a binary number manually, you can extract the binary digits from right to left, multiply each by the corresponding power of 2, and sum them to get the decimal value.

int ConvertToDecimal(string binaryNumber)
{
    int decimalNumber = 0;
    // Iterate over the binary number from right to left
    for (int i = 0; i < binaryNumber.Length; i++)
    {
        // Get the digit (either '0' or '1')
        char digit = binaryNumber[binaryNumber.Length - 1 - i];
        // Convert the digit to an integer (0 or 1) and multiply by the appropriate power of 2
        if (digit == '1')
            decimalNumber += (int)Math.Pow(2, i);  // Add the value of 2^i
    }
    return decimalNumber;
}

The loop goes through each binary digit starting from the rightmost digit. Each binary digit is multiplied by the appropriate power of 2, the result is added to the decimalNumber variable.

int value = ConvertToDecimal("1101"); //13

For manual conversion, iterate through each binary digit, multiply by the corresponding power of 2, and sum the results.