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

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

แปลงเลขฐาน 10 เป็นฐาน 2 โดยการหารซ้ำด้วย 2 และเก็บเศษ

อัลกอริทึม

while (decVal >= 1) {
    val = decVal / 2;
    a += (decVal % 2).ToString();
    decVal = val;
}

จากนั้นอ่านเศษจากหลังมาหน้า (กลับลำดับ string a)

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

using System;
using System.Collections.Generic;
using System.Text;
namespace Demo {
    class MyApplication {
        static void Main(string[] args) {
            int decVal = 34;
            int val;
            string a = "";
            Console.WriteLine("Decimal: {0}", decVal);
            while (decVal >= 1) {
                val = decVal / 2;
                a += (decVal % 2).ToString();
                decVal = val;
            }
            string binValue = "";
            for (int i = a.Length - 1; i >= 0; i--) {
                binValue = binValue + a[i];
            }
            Console.WriteLine("Binary: {0}", binValue);
            Console.Read();
        }
    }
}

ผลลัพธ์

Decimal: 34
Binary: 100010

วิธีทางเลือก (สั้นกว่า):

string binary = Convert.ToString(34, 2); // "100010"