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