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

วิธีแปลงเลขฐานสิบเป็นฐานแปด (Decimal to Octal) ใน C#

ใช้ While Loop หารด้วย 8 ซ้ำๆ เก็บเศษ (Remainder) ไว้ในอาร์เรย์ แล้วนำมาแสดงจากท้ายสุด

อัลกอริทึม

while (dec != 0)
{
    oct[i] = dec % 8;  // เก็บเศษ
    dec = dec / 8;     // หาร 8
    i++;
}

โค้ดตัวอย่างเต็ม (Decimal 18 → Octal 22)

using System;

namespace Demo
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] oct = new int[30];
            int dec = 18;  // เลขฐานสิบ
            int i = 0;
            
            while (dec != 0)
            {
                oct[i] = dec % 8;
                dec = dec / 8;
                i++;
            }
            
            // แสดงจากท้ายสุด (MSB first)
            for (int j = i - 1; j >= 0; j--)
            {
                Console.Write(oct[j]);
            }
            
            Console.ReadKey();
        }
    }
}

ผลลัพธ์

22

วิธีง่ายกว่า: ใช้ Convert.ToString

int dec = 18;
string octal = Convert.ToString(dec, 8); // "22"
Console.WriteLine(octal);

การแปลงฐานอื่นๆ

  • Binary (ฐาน 2): Convert.ToString(dec, 2)
  • Hexadecimal (ฐาน 16): Convert.ToString(dec, 16) หรือ dec.ToString("X")