- Spotlight
23 = 8
Convert Decimal to Binary in C#
What you’ll learn
- How dividing by two and reading remainders reveals binary digits from right to left.
- Why zero needs a special case and why the classic array version prints backwards.
- An MSB-first walk using a bit mask on
uint, a live preview, and the link to binary → decimal.
Overview
Everyday counting uses base ten (digits 0–9). Computers often talk in binary (base two): each position is a power of two, and only digits 0 and 1 appear. To turn a familiar decimal whole number into binary, keep halving it and note whether each step was odd (1) or even (0).
Two programs
Remainder stack in an array (school-style), then bit mask from the top bit down.
Live preview
Nonnegative safe integers; mirrors ToString(2) in spirit.
Inverse
Pair with binary to decimal for the round trip.
Prerequisites
Integer division and modulo, arrays, for loops, and (for Example 2) basic bitwise & and << on uint.
using System;,class Program,Main,Console.Write/WriteLine.uintfor nonnegative patterns avoids signed quirks while halving.
Decimal to binary
Each binary digit is a switch for a power of two: 1 means “add this power,” 0 means “skip it.” To discover those switches from a decimal value, ask repeatedly: “Is my number odd?” That answer is the lowest bit; then divide by two and repeat.
Example: 15 = 8 + 4 + 2 + 1, so in binary it is 11112 (read left to right as 8+4+2+1).
Division recipe
For n ≥ 0: take remainder modulo 2 (that is n % 2), record it, replace n by n / 2 using integer division, and stop when n becomes 0. Read the recorded bits from last to first for the usual MSB-first string.
1515 odd → 1; 7 odd → 1; 3 odd → 1; 1 odd → 1; then done. Reverse list: 1111.
Quick pictures
- Breakdown
4 + 1
Remember: each “odd or even?” question while halving is exactly one binary digit, starting from the right-hand side.
Live preview
Nonnegative integers in JavaScript’s safe range. Uses toString(2) so you can compare with your C# loops.
Algorithm (remainder method)
Goal: print binary digits for nonnegative n, highest place value first.
If n == 0
Print 0 and stop. A bare while (n > 0) loop would print nothing.
Collect bits
While n > 0: save n % 2, then replace n by n / 2.
Print reversed
Output saved bits from last saved down to first.
📜 Pseudocode
function printBinaryFromDecimal(n): // n ≥ 0
if n = 0:
output "0"; return
bits ← empty list
while n > 0:
append (n mod 2) to bits
n ← floor(n / 2)
print bits in reverse order Divide by two with reverse print
Matches the original tutorial idea: stash remainders, then print backward. Adds an explicit zero branch. Uses uint so halving stays nonnegative.
using System;
class Program
{
static void DecimalToBinary(uint decimalNumber)
{
int[] bits = new int[32];
int i = 0;
uint n = decimalNumber;
if (n == 0)
{
Console.WriteLine("Binary equivalent: 0");
return;
}
while (n > 0)
{
bits[i] = (int)(n % 2);
n /= 2;
i++;
}
Console.Write("Binary equivalent: ");
for (int j = i - 1; j >= 0; j--)
{
Console.Write(bits[j]);
}
Console.WriteLine();
}
static void Main()
{
DecimalToBinary(15);
DecimalToBinary(0);
}
} Explanation
The inner loop body repeatedly asks for the lowest bit (% 2) and shifts the value logically (/ 2). The final for loop walks the array from the last bit collected toward the first—the correct reading order for humans.
for (int j = i - 1; j >= 0; j--)MSB first. The highest power of two landed at index i - 1.
MSB-to-LSB with a bit mask
No reversal array: test bit positions 31 down to 0. Skip leading zeros unless the value is 0. Uses unsigned shifts so 1u << 31 is well-defined.
using System;
class Program
{
static void PrintBinaryMsb32(uint n)
{
if (n == 0)
{
Console.Write("0");
return;
}
bool started = false;
for (int b = 31; b >= 0; b--)
{
uint mask = 1u << b;
bool bit = (n & mask) != 0;
if (bit || started)
{
Console.Write(bit ? '1' : '0');
started = true;
}
}
}
static void Main()
{
Console.Write("15 as binary: ");
PrintBinaryMsb32(15);
Console.WriteLine();
Console.Write("64 as binary: ");
PrintBinaryMsb32(64);
Console.WriteLine();
}
} Explanation
started stays false until we meet the first 1, hiding leading zeros. After that, every position prints either 0 or 1.
uint mask = 1u << b;Unsigned literal. Keeps the shift inside the nonnegative mask world your CPU expects for this pattern.
Optimization
Convert.ToString(n, 2). Quick answer for nonnegative int/long when you only need a string.
Find the top bit. On modern .NET you can use BitOperations.Log2 for n > 0 to start the mask loop at the highest set bit instead of always scanning from 31.
Recursive MSB-first. Print DecimalToBinary(n / 2) before n % 2 for n > 0, with a base case for 0—no array required (watch stack depth on huge types).
Interview: mention n == 0, uint for clean bit demos, and link to binary-to-decimal.
❓ FAQ
🔄 Input / output examples
Example 1 uses 15 and 0; Example 2 uses 15 and 64.
| Decimal | Binary (minimal) |
|---|---|
0 | 0 |
1 | 1 |
15 | 1111 |
64 | 1000000 |
Edge cases and pitfalls
Signed integers carry extra rules; these samples stick to nonnegative values so the story stays simple.
n == 0
Must output 0; the naive remainder loop alone prints a blank line.
Minimal vs padded
Sometimes teachers want eight bits (00001111). Say which format you target.
1 << 31 on int
Prefer uint masks like Example 2; shifting into the sign bit of a signed int is easy to get wrong.
Binary to decimal
Practice the reverse journey on the paired C# tutorial.
⏱️ Time and space complexity
| Approach | Time | Extra space |
|---|---|---|
| Remainder + array | O(log n) bits | O(log n) digits stored |
| 32-bit mask scan | O(32) (constant) | O(1) |
Convert.ToString | Linear in output length | Allocates a string |
Here log means base 2 in the sense of bit length for nonnegative n.
Summary
- Idea: peel
n % 2, halven, print collected bits backward—or scan bits from the top with a mask. - Code: guard
0; useuintfor tidy nonnegative bit work. - Pair: binary-to-decimal for the reverse direction.
Each time you divide by 2, the remainder tells you the next bit starting from the right (least significant). Programs usually store those bits and print them backwards so humans read left-to-right from the biggest power of two.
8 people found this page helpful
