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

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

แปลงเลขฐาน 2 เป็นฐาน 10 โดยคูณแต่ละบิตด้วยกำลังของ 2

อัลกอริทึม

while (num > 0) {
    rem = num % 10;           // หาบิตสุดท้าย
    decVal = decVal + rem * baseVal; // บวกค่า
    num = num / 10;           // ตัดบิตสุดท้าย
    baseVal = baseVal * 2;    // เพิ่มกำลังของ 2
}

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

using System;
using System.Collections.Generic;
using System.Text;
namespace Demo {
    class MyApplication {
        static void Main(string[] args) {
            int num = 101;
            int binVal = num;
            int decVal = 0, baseVal = 1, rem;
            while (num > 0) {
                rem = num % 10;
                decVal = decVal + rem * baseVal;
                num = num / 10;
                baseVal = baseVal * 2;
            }
            Console.Write("Binary Number: " + binVal);
            Console.Write("\nDecimal: " + decVal);
            Console.ReadLine();
        }
    }
}

ผลลัพธ์

Binary Number: 101
Decimal: 5

ตรวจสอบ: 1×2² + 0×2¹ + 1×2⁰ = 4 + 0 + 1 = 5 ✓

วิธีทางเลือก: Convert.ToInt32("101", 2) → 5