Để lấy số bát phân từ số thập phân:
Dùng vòng lặp while, lưu phần dư vào mảng bát phân (mod 8), sau đó chia số cho 8:
while (dec != 0) {
oct[i] = dec % 8;
dec = dec / 8;
i++;
}
Ví dụ: Số thập phân 12
using System;
namespace Demo {
class Program {
static void Main(string[] args) {
int[] oct = new int[50];
int dec = 12;
int 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ả: 14 (bát phân của 12).