Convert Binary to Decimal

C++ Program to Convert Binary to Decimal

C++Intermediate
C++
#include <iostream>
#include <cmath>
using namespace std;

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

Output

Enter a binary number: 1010
Binary: 1010 = Decimal: 10

Convert Binary to Decimal in C++

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

What This Program Does

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

  • Input binary: 1010
  • Output decimal: 10

Binary numbers use only digits 0 and 1, while decimal numbers use digits 0-9. The conversion involves multiplying each binary digit by 2 raised to its position power and summing the results.

Example:

  • 1010 (binary) = 1×2³ + 0×2² + 1×2¹ + 0×2⁰ = 8 + 0 + 2 + 0 = 10 (decimal)
  • 1101 (binary) = 1×2³ + 1×2² + 0×2¹ + 1×2⁰ = 8 + 4 + 0 + 1 = 13 (decimal)

Algorithm

The conversion uses a while loop:

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

Step-by-step for binary = 1010:

  1. Extract rightmost digit: 1010 % 10 = 0, decimal = 0 + 0×2⁰ = 0
  2. Remove digit: 1010 / 10 = 101
  3. Extract digit: 101 % 10 = 1, decimal = 0 + 1×2¹ = 2
  4. Continue until all digits processed
  5. Final result: decimal = 10

Understanding Binary System

Positional Value System:

In binary, each position represents a power of 2:

  • Position 0 (rightmost): 2⁰ = 1
  • Position 1: 2¹ = 2
  • Position 2: 2² = 4
  • Position 3: 2³ = 8

Why Binary?:

  • Computers use binary because electronic circuits have two states: on (1) and off (0)
  • All data in computers is ultimately stored in binary format
  • Understanding binary is essential for computer science

Summary

  • Binary-to-decimal conversion multiplies each digit by 2^position and sums the results.
  • Binary is base-2 (uses only 0 and 1), decimal is base-10 (uses 0-9).
  • The algorithm processes digits from right to left (least significant to most significant).
  • Understanding binary is fundamental for computer science and digital systems.

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