将二进制字符串转换为整数的 C# 程序
csharpserver side programmingprogramming更新于 2025/9/24 14:12:00
使用 Convert.ToInt32 类来实现将二进制字符串转换为整数的目的。
假设我们的二进制字符串是 −
string str = "1001";
现在每个字符都被解析为 −
try {
//解析传递的字符串的每个字符
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

