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

แปลง Binary เป็น Decimal ใน C#

แปลงเลขฐาน 2 เป็นฐาน 10 ด้วย While loop คูณกำลังของ 2

อัลกอริทึม

while (val > 0) {
    remainder = val % 10;      // หาบิตสุดท้าย
    decimal = decimal + remainder * baseVal; // บวกค่า
    val = val / 10;            // ตัดบิตสุดท้าย
    baseVal = baseVal * 2;     // กำลังถัดไป
}

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

using System;
using System.Collections.Generic;
using System.Text;
namespace Demo {
    class toBinary {
        static void Main(string[] args) {
            int val = 1010, myBinary, remainder;
            int myDecimal = 0, baseVal = 1;
            myBinary = val;
            while (val > 0) {
                remainder = val % 10;
                myDecimal = myDecimal + remainder * baseVal;
                val = val / 10;
                baseVal = baseVal * 2;
            }
            Console.Write("Binary Number : " + myBinary);
            Console.Write("\nConverted to Decimal: " + myDecimal);
            Console.ReadLine();
        }
    }
}

ผลลัพธ์

Binary Number : 1010
Converted to Decimal: 10

ตรวจสอบ: 1×2³ + 0×2² + 1×2¹ + 0×2⁰ = 8 + 0 + 2 + 0 = 10 ✓

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