Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

โปรแกรม C# แปลงสตริงฐานสองเป็น Integer

แปลงสตริงที่เป็นเลขฐานสอง (เช่น "1001") เป็น integer

วิธีที่ 1: ใช้ Convert.ToInt32 (แนะนำ)

string str = "1001";
int value = Convert.ToInt32(str, 2); // 9

วิธีที่ 2: Parse เอง (โค้ดต้นฉบับ)

public static int Convert(string str1) {
    if (str1 == "") throw new Exception("Invalid input");
    int val = 0, result = 0;
    for (int i = 0; i < str1.Length; i++) {
        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!");
    }
    return result;
}

ตัวอย่างโค้ดเต็ม

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

แนะนำ: ใช้ Convert.ToInt32(str, 2) ซึ่งสั้นกว่า เร็วกว่า และจัดการ error ได้ดีกว่า