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;
   }
}

相关文章

c#如何实现添加到列表代码:var list = new&...
c#循环访问字典代码:foreach(var item in m...
using System; namespace OperatorsAppl { class Program ...
using System; class Program { static void Main(string[...
using System; namespace OperatorsAppl { class Program {...
using System; namespace DeclaringConstants { class Pro...