C#程序将二进制字符串转换为Integer
使用Convert.ToInt32类可以实现将二进制字符串转换为整数的目的。
假设我们的二进制字符串是-
string str = "1001";
现在每个字符都被解析-
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!");
}使用for循环检查以上内容,以检查传递的字符串中的每个字符,即“100”。使用length()方法找到字符串的长度-
str1.Length
示例
您可以尝试运行以下代码,以在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;
}
}输出结果
Integer:9