Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
C# program to convert binary string to Integer
Converting a binary string to an integer in C# can be accomplished using several methods. The most straightforward approach is using Convert.ToInt32() with base 2, but you can also implement manual conversion for better understanding of the binary-to-decimal process.
Using Convert.ToInt32() Method
The simplest way to convert a binary string to an integer is using the built-in Convert.ToInt32() method with base 2 −
using System;
class Program {
static void Main() {
string binaryStr = "1001";
int result = Convert.ToInt32(binaryStr, 2);
Console.WriteLine("Binary: " + binaryStr);
Console.WriteLine("Integer: " + result);
// More examples
Console.WriteLine("1010 = " + Convert.ToInt32("1010", 2));
Console.WriteLine("1111 = " + Convert.ToInt32("1111", 2));
}
}
The output of the above code is −
Binary: 1001 Integer: 9 1010 = 10 1111 = 15
Manual Binary to Integer Conversion
For educational purposes, you can manually convert binary to integer by calculating powers of 2 −
using System;
class Program {
static void Main() {
string binaryStr = "1001";
int result = ManualConvert(binaryStr);
Console.WriteLine("Binary: " + binaryStr);
Console.WriteLine("Integer: " + result);
}
static int ManualConvert(string binaryStr) {
int result = 0;
for (int i = 0; i < binaryStr.Length; i++) {
char bit = binaryStr[i];
if (bit == '1') {
int power = binaryStr.Length - 1 - i;
result += (int)Math.Pow(2, power);
}
else if (bit != '0') {
throw new ArgumentException("Invalid binary string");
}
}
return result;
}
}
The output of the above code is −
Binary: 1001 Integer: 9
Using LINQ for Conversion
Here's a more concise approach using LINQ −
using System;
using System.Linq;
class Program {
static void Main() {
string binaryStr = "1101";
int result = binaryStr
.Select((bit, index) => bit == '1' ? (int)Math.Pow(2, binaryStr.Length - 1 - index) : 0)
.Sum();
Console.WriteLine("Binary: " + binaryStr);
Console.WriteLine("Integer: " + result);
}
}
The output of the above code is −
Binary: 1101 Integer: 13
Comparison of Methods
| Method | Advantages | Use Case |
|---|---|---|
| Convert.ToInt32() | Built-in, fast, handles errors | Production code |
| Manual conversion | Educational, customizable | Learning binary concepts |
| LINQ approach | Concise, functional style | When LINQ is preferred |
Conclusion
Converting binary strings to integers in C# is most efficiently done using Convert.ToInt32(binaryString, 2). Manual conversion helps understand the underlying mathematical process, while LINQ provides a functional programming approach for those who prefer it.
