Convert Binary to Decimal in C#

Beginner
⏱️ 11 min read
📚 Updated: May 2026
🎯 2 Code Examples
Base conversion

What you’ll learn

  • How place value turns a binary bit pattern into a decimal whole number.
  • Two C# styles: digit peel (integer that looks like 101010) and Horner on a string.
  • Why doubling a weight beats Math.Pow here, how to validate digits, and a browser live preview.

Overview

Binary counts with powers of two from the rightmost bit (the ones place in base two). This page shows the same math two ways in C#: peel digits from a “binary-looking” integer, or scan a string of '0' and '1' characters with Horner’s rule.

Two programs

Digit peel (classic homework shape, hardened) plus string Horner.

Live preview

Type a bit string; see decimal via parseInt(..., 2) for a quick check.

Fixes vs naive Math.Pow

Exact integer weights, digit checks, and long accumulators where helpful.

Prerequisites

Loops, integer division and modulo, and the idea of place value (ones, twos, fours, …).

  • using System;, a console program with static void Main(), and Console.WriteLine.
  • Optional: string, foreach, and Try patterns for safe parsing.

What does binary to decimal mean?

Each bit position i (starting at 0 on the right) contributes bi · 2i where bi is 0 or 1. The decimal value is the sum of those contributions.

Example 1 stores the pattern as a normal decimal integer 101010 so each base-ten digit is one bit; the loop reads bits from right to left.

Binary base 2
Decimal base 10
Example 1010102 = 42

Expanded form

Reading 101010 from most to least significant bit (left to right as written),

1010102

1·25 + 0·24 + 1·23 + 0·22 + 1·21 + 0·20 = 32 + 8 + 2 = 42.

Intuition

10102 Decimal 10
Sum
8 + 2 = 10
1112 Decimal 7
Sum
4 + 2 + 1 = 7

Takeaway: each 1 turns on a power of two; each 0 skips that power.

Live preview

Enter a string of 0 and 1 characters (optional spaces). Uses parseInt(s, 2) for a quick decimal value. Empty or invalid characters are rejected.

For long strings, JavaScript may lose precision past 53 bits.

Live result
Press “Convert” to see the decimal value.

Algorithm (digit-stored form)

Goal: interpret a nonnegative integer whose decimal digits are only 0 or 1 as a binary pattern and return its decimal value.

Validate digits

Every decimal digit of n must be 0 or 1.

Start value = 0, weight 1

Weight doubles each step: 1, 2, 4, …

While the working number is nonzero

Take d = n % 10, add d * weight to value, divide n by 10, multiply weight by 2.

📜 Pseudocode

Pseudocode
function binaryDigitsToDecimal(n):  // n has only 0/1 decimal digits
    value ← 0
    weight ← 1
    while n > 0:
        d ← n mod 10
        if d not in {0, 1}: return error
        value ← value + d * weight
        n ← floor(n / 10)
        weight ← weight * 2
    return value
1

Digit peel (integer 101010, no Math.Pow)

Same idea as the original tutorial, but uses an exact doubling weight, validates digits, and uses TryBinaryDigitsToDecimal instead of a magic return value.

c#
using System;

class Program
{
    static bool HasOnlyBinaryDigits(long n)
    {
        if (n < 0)
        {
            return false;
        }
        if (n == 0)
        {
            return true;
        }
        while (n > 0)
        {
            long d = n % 10;
            if (d > 1)
            {
                return false;
            }
            n /= 10;
        }
        return true;
    }

    static bool TryBinaryDigitsToDecimal(long binaryForm, out long decimalValue)
    {
        decimalValue = 0;
        if (!HasOnlyBinaryDigits(binaryForm))
        {
            return false;
        }

        long weight = 1;
        long n = binaryForm;
        while (n > 0)
        {
            int digit = (int)(n % 10);
            decimalValue += (long)digit * weight;
            n /= 10;
            weight *= 2;
        }

        return true;
    }

    static void Main()
    {
        long binaryNumber = 101010;

        if (!TryBinaryDigitsToDecimal(binaryNumber, out long decimalNumber))
        {
            Console.WriteLine("Invalid binary digit pattern.");
            return;
        }

        Console.WriteLine($"Binary: {binaryNumber}");
        Console.WriteLine($"Decimal: {decimalNumber}");
    }
}

Explanation

The rightmost decimal digit of 101010 is the ones bit in binary, so the first peeled digit pairs with weight 1, then 2, then 4, and so on.

weight *= 2;

Exact powers of two. Avoids floating-point Math.Pow rounding.

HasOnlyBinaryDigits

Reject garbage. A digit 29 must not be treated as a bit.

2

Horner’s method on a bit string

Natural when input is text: process the most significant bit first without reversing the string.

c#
using System;

class Program
{
    static bool TryBinaryStringToDecimal(string? s, out long decimalValue)
    {
        decimalValue = 0;
        if (string.IsNullOrEmpty(s))
        {
            return false;
        }

        foreach (char c in s)
        {
            if (c != '0' && c != '1')
            {
                return false;
            }
            decimalValue = decimalValue * 2 + (c - '0');
        }

        return true;
    }

    static void Main()
    {
        string bits = "101010";

        if (!TryBinaryStringToDecimal(bits, out long dec))
        {
            Console.WriteLine("Invalid binary string.");
            return;
        }

        Console.WriteLine($"Binary (string): {bits}");
        Console.WriteLine($"Decimal: {dec}");
    }
}

Explanation

Each step doubles the running total (like shifting left in binary) and adds the new bit.

decimalValue = decimalValue * 2 + (c - '0');

Horner update. Same algebra as value = (value << 1) | bit for unsigned bit variables.

Optimization

Library parsing. For trusted input, Convert.ToInt64(s, 2) or Convert.ToUInt64 can parse a binary string in one call (still handle format exceptions).

Literals. When the pattern is fixed in code, 0b101010 is already the decimal value 42—no conversion loop needed.

Very long strings. Use System.Numerics.BigInteger if values exceed long.

Interview: explain both LSD peel and Horner; mention validation and overflow.

❓ FAQ

The classroom-style trick stores the bit pattern as a decimal integer whose digits are only 0 and 1. The code peels digits with % 10. In real C# you can also write the literal 0b101010 (binary integer literal) or parse a string with Convert.ToInt64(s, 2) depending on the task.
Math.Pow returns double. Large i can round wrong before you cast back to integer. Multiplying a running weight by 2 each step stays exact for typical sizes.
That is not a valid binary digit. The samples validate each peeled digit (or each character) so values like 102 are rejected instead of misinterpreted.
Scan left to right: start at 0, then for each character c, value = value * 2 + (c - '0'). That matches reading the string most-significant bit first without reversing.
Yes. Many bits can exceed long range. Widen your strategy (BigInteger, checked arithmetic, or bounds checks) when inputs can be huge.
Linear in the number of bits or digits: O(k) for k binary digits.

🔄 Input / output examples

Example 1 prints the digit-form value and decimal. Example 2 labels the string form.

Input formMeaningDecimal
101010 (long)Six-bit pattern42
"101010" stringSame pattern42
102Invalid digit 2Error (Try method fails)

Edge cases and pitfalls

Mixing up the digit-stored integer with a binary literal is the main conceptual trap; invalid digits and overflow are the main engineering traps.

Meaning

101010 in source code

Without a prefix, that token is a decimal integer one hundred one thousand ten. The peel routine treats its digits as bits. The literal 0b101010 is different: it already means 42.

Digits

Values outside {0,1}

Without validation, a digit like 9 would add 9 · 2k in the peel loop—not a binary interpretation.

Floats

Math.Pow(2, i)

Can mis-round for large i. Prefer integer doubling or exact shifts.

Length

Very long bit strings

Horner on long overflows when the true value exceeds the type; switch to BigInteger or a bounded policy.

⏱️ Time and space complexity

ApproachTimeExtra space
Digit peel or Horner on k bitsO(k)O(1)

Both sample programs use only a few scalars besides input storage.

Summary

  • Math: sum of bi 2i for bits bi.
  • Code: digit peel with doubling weight, or Horner on a string; skip naive Math.Pow for exact integers.
  • Watch-outs: meaning of 101010 vs 0b101010, digit validation, overflow on long inputs.
Did you know?

The pattern 101010 in base two means 32 + 8 + 2 = 42 in base ten. In Example 1, that pattern is stored as the ordinary decimal integer 101010 so each base-ten digit is a binary bit; it is not the same as writing the C# binary literal 0b101010 (that literal already means 42 in source code).

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

9 people found this page helpful