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

วิธีแปลงเลขฐานสิบเป็นฐานสองใน C#

แปลงเลข 48 เป็นฐานสอง ใช้หารและโมดูลู 2 ในลูป while

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

จากนั้นกลับลำดับสตริงได้ผลลัพธ์

ตัวอย่าง

using System;
using System.Collections.Generic;
using System.Text;
namespace Demo {
    class MyApplication {
        static void Main(string[] args) {
            int decVal, val;
            string a = "";
            decVal = 48;
            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 = 48
Binary = 110000