C# Program to Convert Decimal to Binary Number
Convert.ToString(decimalNumber, 2) or by repeatedly dividing the number by 2 and collecting remainders.Examples
How to Think About It
Algorithm
Code
using System; class Program { static void Main() { int decimalNumber = 10; string binary = Convert.ToString(decimalNumber, 2); Console.WriteLine(binary); } }
Dry Run
Let's trace the decimal number 10 through the conversion using division and remainder.
Initial number
decimalNumber = 10
Divide by 2 and get remainder
10 / 2 = 5 remainder 0
Divide quotient by 2 and get remainder
5 / 2 = 2 remainder 1
Divide quotient by 2 and get remainder
2 / 2 = 1 remainder 0
Divide quotient by 2 and get remainder
1 / 2 = 0 remainder 1
Collect remainders in reverse
Remainders: 1 0 1 0 → binary = "1010"
| Quotient | Remainder |
|---|---|
| 10 | 0 |
| 5 | 1 |
| 2 | 0 |
| 1 | 1 |
Why This Works
Step 1: Using Convert.ToString
The method Convert.ToString(number, 2) converts the decimal number directly to its binary string representation.
Step 2: Manual division method
Dividing the number by 2 repeatedly and collecting remainders builds the binary digits from least significant to most significant.
Step 3: Reversing remainders
Reading the collected remainders in reverse order gives the correct binary number.
Alternative Approaches
using System; using System.Text; class Program { static void Main() { int decimalNumber = 10; StringBuilder binary = new StringBuilder(); int number = decimalNumber; if (number == 0) binary.Append('0'); while (number > 0) { binary.Insert(0, number % 2); number /= 2; } Console.WriteLine(binary.ToString()); } }
using System; class Program { static void Main() { int decimalNumber = 10; Console.WriteLine(ToBinary(decimalNumber)); } static string ToBinary(int n) { if (n == 0) return "0"; if (n == 1) return "1"; return ToBinary(n / 2) + (n % 2).ToString(); } }
Complexity: O(log n) time, O(log n) space
Time Complexity
The number of divisions by 2 is proportional to the number of binary digits, which is about log base 2 of the number.
Space Complexity
Storing the binary digits requires space proportional to the number of bits, also about log base 2 of the number.
Which Approach is Fastest?
Using Convert.ToString is fastest and simplest, while manual or recursive methods are more educational but less efficient.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Convert.ToString | O(log n) | O(log n) | Quick and simple conversion |
| Manual loop | O(log n) | O(log n) | Learning and understanding process |
| Recursion | O(log n) | O(log n) | Elegant code but less efficient for large inputs |
Convert.ToString(number, 2) for a quick and reliable decimal to binary conversion in C#.