- Sum
8 + 2 = 10
Convert Binary to Decimal in C#
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.Powhere, 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 withstatic void Main(), andConsole.WriteLine.- Optional:
string,foreach, andTrypatterns 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.
Expanded form
Reading 101010 from most to least significant bit (left to right as written),
10101021·25 + 0·24 + 1·23 + 0·22 + 1·21 + 0·20 = 32 + 8 + 2 = 42.
Intuition
- 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.
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.
String form (Horner)
Scan left to right: value = value * 2 + (c - '0') for each c in '0' or '1'.
📜 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 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.
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.
HasOnlyBinaryDigitsReject garbage. A digit 2–9 must not be treated as a bit.
Horner’s method on a bit string
Natural when input is text: process the most significant bit first without reversing the string.
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
🔄 Input / output examples
Example 1 prints the digit-form value and decimal. Example 2 labels the string form.
| Input form | Meaning | Decimal |
|---|---|---|
101010 (long) | Six-bit pattern | 42 |
"101010" string | Same pattern | 42 |
102 | Invalid digit 2 | Error (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.
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.
Values outside {0,1}
Without validation, a digit like 9 would add 9 · 2k in the peel loop—not a binary interpretation.
Math.Pow(2, i)
Can mis-round for large i. Prefer integer doubling or exact shifts.
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
| Approach | Time | Extra space |
|---|---|---|
Digit peel or Horner on k bits | O(k) | O(1) |
Both sample programs use only a few scalars besides input storage.
Summary
- Math: sum of
bi 2ifor bitsbi. - Code: digit peel with doubling weight, or Horner on a string; skip naive
Math.Powfor exact integers. - Watch-outs: meaning of
101010vs0b101010, digit validation, overflow on long inputs.
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).
9 people found this page helpful
