Convert Decimal to Binary

Decimal to Binary Conversion in C++ (5 Programs)

IntermediateTopic: Advanced Number Programs
Back

C++ Convert Decimal to Binary Program

This program helps you to learn the fundamental structure and syntax of C++ programming.

Try This Code
#include <iostream>
using namespace std;

int main() {
    int decimal;
    long long binary = 0;
    int remainder, i = 1;
    
    cout << "Enter a decimal number: ";
    cin >> decimal;
    
    int temp = decimal;
    
    while (temp != 0) {
        remainder = temp % 2;
        temp /= 2;
        binary += remainder * i;
        i *= 10;
    }
    
    cout << "Decimal: " << decimal << " = Binary: " << binary << endl;
    
    return 0;
}
Output
Enter a decimal number: 10
Decimal: 10 = Binary: 1010

Understanding Convert Decimal to Binary

This program teaches you how to convert a decimal number to its binary (base-2) equivalent in C++. Binary is the fundamental number system used by computers, where each digit can only be 0 or 1. Understanding decimal-to-binary conversion is essential for computer science, digital systems, and understanding how computers store and process numbers.

---

1. What This Program Does

The program converts a decimal number (base-10) to a binary number (base-2). For example:

Input decimal: 10
Output binary: 1010

The conversion involves repeatedly dividing the decimal number by 2 and collecting the remainders. The binary number is formed by reading the remainders in reverse order (from last to first).

Example:

10 (decimal) → divide by 2 repeatedly → remainders: 0, 1, 0, 1 → reverse → 1010 (binary)
15 (decimal) → remainders: 1, 1, 1, 1 → reverse → 1111 (binary)

---

2. Header File Used

This header provides:

cout for displaying output
cin for taking input from the user

---

#include <iostream>

3. Declaring Variables

The program declares:

int decimal;

long long binary = 0;

int remainder, i = 1;

decimal stores the decimal number entered by the user.
binary stores the converted binary result (initialized to 0, long long for large results).
remainder stores the remainder from each division by 2.
i is a multiplier that represents the current position (1, 10, 100, 1000, ...).

---

4. Taking Input From the User

The program asks:

cin >> decimal;

The user enters a decimal number, for example: 10

We also create a temporary copy:

int temp = decimal;

This is important because we'll modify the number during conversion, and we need the original for display.

---

cout << "Enter a decimal number: ";

5. The Conversion Algorithm

The core conversion uses a while loop:

while (temp != 0) {

remainder = temp % 2;

temp /= 2;

binary += remainder * i;

i *= 10;

}

Let's break down how this works step-by-step for decimal = 10:

Step 1:

remainder = 10 % 2 = 0 (remainder when dividing by 2)
temp = 10 / 2 = 5 (quotient after dividing by 2)
binary = 0 + 0 × 1 = 0
i = 1 × 10 = 10 (move to next position)

Step 2:

remainder = 5 % 2 = 1
temp = 5 / 2 = 2
binary = 0 + 1 × 10 = 10
i = 10 × 10 = 100

Step 3:

remainder = 2 % 2 = 0
temp = 2 / 2 = 1
binary = 10 + 0 × 100 = 10
i = 100 × 10 = 1000

Step 4:

remainder = 1 % 2 = 1
temp = 1 / 2 = 0
binary = 10 + 1 × 1000 = 1010
i = 1000 × 10 = 10000

Step 5:

temp is now 0, so the loop stops
Final result: binary = 1010

---

6. Understanding the Conversion Process

Why Divide by 2?

:

Binary is base-2, so we divide by 2 repeatedly.
Each division extracts one binary digit (0 or 1) as the remainder.
The quotient becomes the new number to process.

Why Read Remainders in Reverse?

:

The first remainder is the least significant bit (rightmost).
The last remainder is the most significant bit (leftmost).
We build the binary number by placing remainders from right to left.

Visual Example

(for decimal = 10):

Step 1: 10 ÷ 2 = 5 remainder 0 → binary digit: 0
Step 2: 5 ÷ 2 = 2 remainder 1 → binary digit: 1
Step 3: 2 ÷ 2 = 1 remainder 0 → binary digit: 0
Step 4: 1 ÷ 2 = 0 remainder 1 → binary digit: 1
Reading remainders from bottom to top: 1, 0, 1, 0
Result: 1010 (binary)

---

7. How the Binary Number is Built

Position Multiplier (i)

:

i starts at 1 (ones place).
Each iteration, i is multiplied by 10 (moves to next position).
i values: 1, 10, 100, 1000, 10000, ...

Building Process

:

remainder * i places the digit at the correct position.
Example: remainder = 1, i = 1000 → adds 1000 to binary (places 1 at thousands place).
Each new remainder is placed to the left of previous digits.

Why Multiply i by 10?

:

We're building a number where each position is 10 times the previous.
This creates: ones, tens, hundreds, thousands, ...
Matches how we write numbers (right to left: ones, tens, hundreds, ...).

---

8. Other Methods (Mentioned but not shown in code)

Method 2: Using Recursion

long long decimalToBinary(int decimal) {

if (decimal == 0) return 0;

}

Recursive approach - function calls itself.
Base case: when decimal becomes 0, return 0.
Recursive case: get remainder, recurse on quotient, then combine.
    return (decimal % 2) + 10 * decimalToBinary(decimal / 2);

Method 3: Using bitset

bitset<32> binary(decimal);

cout << binary.to_string();

bitset is a C++ class for handling binary numbers.
Automatically converts decimal to binary.
Can specify number of bits (e.g., 32 bits).
#include <bitset>

Method 4: Using String

string binary = "";

while (decimal > 0) {

binary = to_string(decimal % 2) + binary;

decimal /= 2;

}

Builds binary as a string.
Prepends each remainder to the string.
More flexible for very large numbers.

Method 5: Using Bit Manipulation

string binary = "";

for (int i = 31; i >= 0; i--) {

binary += ((decimal >> i) & 1) ? '1' : '0';

}

Uses bitwise right shift (>>) and bitwise AND (&).
Extracts each bit from the number.
More advanced, works at the bit level.

---

9. Displaying the Result

The program prints:

Output:

Decimal: 10 = Binary: 1010

This clearly shows both the original decimal number and its binary equivalent.

---

cout << "Decimal: " << decimal << " = Binary: " << binary << endl;

10. Understanding the Division Process

Repeated Division by 2

:

Each division by 2 extracts one binary digit.
The remainder (0 or 1) is the binary digit.
The quotient is used for the next iteration.

When Does It Stop?

:

The process stops when the quotient becomes 0.
At this point, all binary digits have been extracted.

Example Trace

(for decimal = 10):

Step 1: 10 ÷ 2 = 5 remainder 0 → binary digit: 0
Step 2: 5 ÷ 2 = 2 remainder 1 → binary digit: 1
Step 3: 2 ÷ 2 = 1 remainder 0 → binary digit: 0
Step 4: 1 ÷ 2 = 0 remainder 1 → binary digit: 1
Step 5: 0 (stop)
Reading remainders from last to first: 1, 0, 1, 0 → 1010

---

11. Common Decimal to Binary Conversions

Small Numbers

:

0 (decimal) = 0 (binary)
1 (decimal) = 1 (binary)
2 (decimal) = 10 (binary)
3 (decimal) = 11 (binary)
4 (decimal) = 100 (binary)
5 (decimal) = 101 (binary)
8 (decimal) = 1000 (binary)
10 (decimal) = 1010 (binary)
15 (decimal) = 1111 (binary)
16 (decimal) = 10000 (binary)

Pattern Recognition

:

Powers of 2 have single 1 followed by zeros: 2=10, 4=100, 8=1000, 16=10000
Numbers one less than power of 2 are all 1s: 3=11, 7=111, 15=1111

---

12. When to Use Each Method

-

While Loop

: Best for learning - clear and straightforward, shows the algorithm.

-

Recursion

: Educational - helps understand recursive thinking.

-

bitset

: Best for simplicity - one line, handles conversion automatically.

-

String

: Good for very large numbers - more flexible.

-

Bit Manipulation

: Most efficient - works at hardware level, advanced.

Best Practice

: Use while loop for learning, bitset for simplicity, or bit manipulation for efficiency.

---

13. Important Considerations

Integer Overflow

:

Binary representation can be very long.
long long is used to handle larger binary numbers.
For very large decimals, consider using string method.

Leading Zeros

:

This method doesn't produce leading zeros.
Example: 5 (decimal) = 101 (binary), not 00000101.
If you need fixed width, use bitset or pad with zeros.

Negative Numbers

:

This implementation doesn't handle negative numbers.
For negative numbers, use two's complement representation.
Or convert absolute value and add sign bit.

---

14. return 0;

This ends the program successfully.

---

Summary

Decimal-to-binary conversion repeatedly divides by 2 and collects remainders.
Remainders are read in reverse order (last to first) to form the binary number.
The algorithm processes from most significant to least significant digits.
Binary uses only digits 0 and 1 (base-2 number system).
Understanding this conversion is essential for computer science and digital systems.
Multiple methods exist: while loop, recursion, bitset, string, bit manipulation.
Choose method based on needs: learning vs. simplicity vs. efficiency.

This program is fundamental for beginners learning number systems, understanding how computers represent numbers internally, and preparing for more advanced topics in computer science, digital systems, and low-level programming in C++ programs.

Let us now understand every line and the components of the above program.

Note: To write and run C++ programs, you need to set up the local environment on your computer. Refer to the complete article Setting up C++ Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your C++ programs.

Practical Learning Notes for Convert Decimal to Binary

This C++ program is part of the "Advanced Number Programs" topic and is designed to help you build real problem-solving confidence, not just memorize syntax. Start by understanding the goal of the program in plain language, then trace the logic line by line with a custom input of your own. Once you can predict the output before running the code, your understanding becomes much stronger.

A reliable practice pattern is to run the original version first, then modify only one condition or variable at a time. Observe how that single change affects control flow and output. This deliberate style helps you understand loops, conditions, and data movement much faster than copying full solutions repeatedly.

For interview preparation, explain this solution in three layers: the high-level approach, the step-by-step execution, and the time-space tradeoff. If you can teach these three layers clearly, you are ready to solve close variations of this problem under time pressure.

Table of Contents