
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
C# program to convert binary string to Integer
Use the Convert.ToInt32 class to fulfill your purpose of converting a binary string to an integer.
Let’s say our binary string is −
string str = "1001";
Now each char is parsed −
try { //Parse each char of the passed string val = Int32.Parse(str1[i].ToString()); if (val == 1) result += (int) Math.Pow(2, str1.Length - 1 - i); else if (val > 1) throw new Exception("Invalid!"); } catch { throw new Exception("Invalid!"); }
Check the above for each character in the passed string i.e. “100” using a for a loop. Find the length of the string using the length() method −
str1.Length
Example
You can try to run the following code to convert a binary string to an integer in C#.
using System; class Program { static void Main() { string str = "1001"; Console.WriteLine("Integer:"+ConvertClass.Convert(str)); } } public static class ConvertClass { public static int Convert(string str1) { if (str1 == "") throw new Exception("Invalid input"); int val = 0, res = 0; for (int i = 0; i < str1.Length; i++) { try { val = Int32.Parse(str1[i].ToString()); if (val == 1) res += (int)Math.Pow(2, str1.Length - 1 - i); else if (val > 1) throw new Exception("Invalid!"); } catch { throw new Exception("Invalid!"); } } return res; } }
Output
Integer:9
- Related Questions & Answers
- C# Program to Convert Integer to String
- C# Program to convert integer array to string array
- Java Program to convert an integer into binary
- Java Program to convert from integer to String
- Java Program to convert from String to integer
- Golang Program to convert an integer into binary representation
- Java Program to convert int to binary string
- Java Program to convert String to Integer using Integer.parseInt()
- Java Program to convert integer to String with Map
- C# Program to Convert Binary to Decimal
- C# Program to Convert Decimal to Binary
- C# program to convert floating to binary
- Convert a String to Integer Array in C/C++
- How to convert String to Integer and Integer to String in Java?
- How to convert a string to a integer in C
Advertisements