C# 程序,将二进制字符串转换为整数
使用 Convert.ToInt32 类实现将二进制字符串转换为整数的目的。
假设我们的二进制字符串是 −
string str = "1001";
现在解析每个 char −
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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP