將二進位制字串轉換為整數的 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