Để chuyển Decimal sang Binary dùng đệ quy:
int dec = 30;
Hàm đệ quy:
public int DisplayBinary(int dec)
{
int res;
if (dec != 0)
{
res = (dec % 2) + 10 * DisplayBinary(dec / 2);
Console.Write(res);
return 0;
}
else
{
return 0;
}
}
Ví dụ hoàn chỉnh
using System;
public class Program
{
public static void Main(string[] args)
{
int dec = 30;
Demo d = new Demo();
Console.Write("Decimal = " + dec);
Console.Write("\nBinary of {0} = ", dec);
d.DisplayBinary(dec);
Console.ReadLine();
Console.Write("\n");
}
}
public class Demo
{
public int DisplayBinary(int dec)
{
int res;
if (dec != 0)
{
res = (dec % 2) + 10 * DisplayBinary(dec / 2);
Console.Write(res);
return 0;
}
else
{
return 0;
}
}
}
Kết quả
Decimal = 30 Binary of 30 = 11110
Giải thích: Đệ quy chia liên tục cho 2, lấy phần dư (0 hoặc 1), xây dựng số binary bằng cách nhân 10 và cộng dồn. Cách hiện đại hơn: Convert.ToString(30, 2) trả về "11110".