Convert Decimal to Binary in C#

Beginner
⏱️ 9 min read
📚 Updated: May 2026
🎯 2 Code Examples
Base conversion

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 09). 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.
  • uint for 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).

Decimal base 10
Binary base 2
Example 15 → 1111

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.

15

15 odd → 1; 7 odd → 1; 3 odd → 1; 1 odd → 1; then done. Reverse list: 1111.

Quick pictures

8 1000₂
Spotlight
23 = 8
5 101₂
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.

Negative values are rejected; signed two's complement is a different lesson.

Live result
Press “Show binary” to convert.

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

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
1

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.

c#
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.

2

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.

c#
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

The first remainder from dividing by 2 is the ones place (least significant bit). Later remainders are higher powers of two. Printing from last remainder to first walks from the biggest bit down to the smallest.
A plain while (n > 0) loop never runs when n is 0, so nothing gets printed. Treat 0 as a special case and output a single 0.
It checks powers of two from high to low (here 31 down to 0 for a 32-bit pattern). It skips leading zeros unless the value is 0. You do not need an array to reverse digits.
Simple division on signed int does not give a pretty "binary string" for negatives. For raw bits, cast to uint (unchecked) for the same width, or use Convert.ToString with care—and say what rule you use.
Either minimal width (no leading zeros except the number 0) or a fixed width (like 8 or 32 bits). Say which one your assignment wants.
For nonnegative integers that fit in int or long, Convert.ToString(n, 2) returns a minimal binary string. Interviews still expect you to explain division-by-two or bit tests.
About O(number of bits): roughly log2(n) divisions for the remainder method, or O(32) for a fixed-width scan.

🔄 Input / output examples

Example 1 uses 15 and 0; Example 2 uses 15 and 64.

DecimalBinary (minimal)
00
11
151111
641000000

Edge cases and pitfalls

Signed integers carry extra rules; these samples stick to nonnegative values so the story stays simple.

Zero

n == 0

Must output 0; the naive remainder loop alone prints a blank line.

Width

Minimal vs padded

Sometimes teachers want eight bits (00001111). Say which format you target.

Shift

1 << 31 on int

Prefer uint masks like Example 2; shifting into the sign bit of a signed int is easy to get wrong.

Inverse

Binary to decimal

Practice the reverse journey on the paired C# tutorial.

⏱️ Time and space complexity

ApproachTimeExtra space
Remainder + arrayO(log n) bitsO(log n) digits stored
32-bit mask scanO(32) (constant)O(1)
Convert.ToStringLinear in output lengthAllocates a string

Here log means base 2 in the sense of bit length for nonnegative n.

Summary

  • Idea: peel n % 2, halve n, print collected bits backward—or scan bits from the top with a mask.
  • Code: guard 0; use uint for tidy nonnegative bit work.
  • Pair: binary-to-decimal for the reverse direction.
Did you know?

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.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful