C# program to convert binary string to Integer

CsharpServer Side ProgrammingProgramming

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#.

Live Demo

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
raja
Published on 24-Jul-2018 17:04:23
Advertisements