ใช้คลาส 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!");
} ตรวจสอบด้านบนสำหรับอักขระแต่ละตัวในสตริงที่ส่งผ่าน เช่น "100" โดยใช้ a for a loop ค้นหาความยาวของสตริงโดยใช้วิธี 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