Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Chuyển đổi Decimal sang Octal (bát phân) trong C#


Dùng while loop lấy phần dư mod 8, lưu vào mảng octal, chia 8 cho đến khi dec=0.

while (dec != 0) { oct[i] = dec % 8; dec = dec / 8; i++; }

Ví dụ

using System;
namespace Demo {
    class Program {
        static void Main(string[] args) {
            int[] oct = new int[30];
            int dec = 18, i = 0;
            while (dec != 0) { oct[i] = dec % 8; dec = dec / 8; i++; }
            for (int j = i-1; j >= 0; j--) Console.Write(oct[j]);
            Console.ReadKey();
        }
    }
}

Kết quả: 22 (octal của 18).