Convert Binary to Decimal program in C++

Convert Binary to Decimal program

Given: Binary number as input and we have to convert it to decimal number.

This can be done by multiplying each digit of binary number starting from LSB with powers of 2 respectively.

Example:

Binary number: 100101

(1*2^5) + (0*2^4)+ (0*2^3)+ (1*2^2)+ (0*2^1)+ (1*2^0) = 37

Decimal number =37

# Algorithm

  1. Prompt the user to enter a binary number.
  2. Initialize a variable result to 0.
  3. For each digit in the binary number, starting from the least significant digit: a. Multiply the digit by 2 raised to the power of its position in the number (starting from 0 for the least significant digit). b. Add the result of the multiplication to result.
  4. Output the value of result as the decimal equivalent of the binary number.

Code:

#include <iostream>
#include <math.h>

using namespace std;

int main() {
  long int i, no;
  int x, result = 0;

  cout << "Enter any binary number: ";
  cin >> no;

  cout << "\nThe decimal conversion of " << no << " is ";

  for (i = 0; no != 0; i++) {
    x = no % 10;
    result = (x) *(pow(2, i)) + result;
    no = no / 10;
  }

  cout << result;

  return 0;
}

Output

Enter any binary number: 10101
The decimal conversion of 10101 is 21
Convert Binary to Decimal program in C++