Convert Decimal to Binary

Decimal to Binary Conversion in C++

C++Intermediate
C++
#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

Convert Decimal to Binary in C++

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.

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)

Algorithm

The conversion uses a while loop:

cpp
while (temp != 0) {
    remainder = temp % 2;
    temp /= 2;
    binary += remainder * i;
    i *= 10;
}

Step-by-step for decimal = 10:

  1. Divide by 2: 10 % 2 = 0, binary = 0, i = 10
  2. Divide by 2: 5 % 2 = 1, binary = 10, i = 100
  3. Divide by 2: 2 % 2 = 0, binary = 10, i = 1000
  4. Divide by 2: 1 % 2 = 1, binary = 1010, i = 10000
  5. Final result: binary = 1010

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

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 fundamental for computer science and digital systems.

This program is essential for understanding number systems, computer architecture, and how computers represent and process data.