C# Program to Convert Binary to Decimal Number
Convert.ToInt32(binaryString, 2), for example: int decimalValue = Convert.ToInt32("1010", 2); converts binary "1010" to decimal 10.Examples
How to Think About It
Algorithm
Code
using System; class Program { static void Main() { string binaryString = "1010"; int decimalValue = Convert.ToInt32(binaryString, 2); Console.WriteLine(decimalValue); } }
Dry Run
Let's trace the binary string "1010" through the code.
Input binary string
binaryString = "1010"
Convert binary to decimal
decimalValue = Convert.ToInt32("1010", 2) which calculates 1*2^3 + 0*2^2 + 1*2^1 + 0*2^0 = 8 + 0 + 2 + 0 = 10
Print decimal value
Output: 10
| Index (from right) | Digit | Calculation | Running Total |
|---|---|---|---|
| 0 | 0 | 0 * 2^0 = 0 | 0 |
| 1 | 1 | 1 * 2^1 = 2 | 2 |
| 2 | 0 | 0 * 2^2 = 0 | 2 |
| 3 | 1 | 1 * 2^3 = 8 | 10 |
Why This Works
Step 1: Using Convert.ToInt32
The method Convert.ToInt32(string, 2) converts a binary string directly to an integer by interpreting it as base 2.
Step 2: Binary to decimal logic
Each binary digit is multiplied by 2 raised to its position index, starting from zero on the right, then summed to get the decimal value.
Step 3: Output the result
The decimal integer is printed using Console.WriteLine, showing the converted number.
Alternative Approaches
using System; class Program { static void Main() { string binary = "1010"; int decimalValue = 0; int power = 1; for (int i = binary.Length - 1; i >= 0; i--) { if (binary[i] == '1') { decimalValue += power; } power *= 2; } Console.WriteLine(decimalValue); } }
using System; using System.Linq; class Program { static void Main() { string binary = "1010"; int decimalValue = binary.Aggregate(0, (acc, c) => acc * 2 + (c - '0')); Console.WriteLine(decimalValue); } }
Complexity: O(n) time, O(1) space
Time Complexity
The conversion processes each character of the binary string once, so it takes linear time relative to the string length.
Space Complexity
The method uses constant extra space, only storing a few variables regardless of input size.
Which Approach is Fastest?
Using Convert.ToInt32 is fastest and simplest; manual loops or LINQ add overhead and complexity.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Convert.ToInt32 | O(n) | O(1) | Quick and simple conversion |
| Manual loop | O(n) | O(1) | Learning and understanding logic |
| LINQ Aggregate | O(n) | O(1) | Functional style, concise code |
Convert.ToInt32(binaryString, 2) for a quick and reliable binary to decimal conversion in C#.Convert.ToInt32, causing errors or wrong results.