C++ Program to Convert Binary to Decimal

Conversion Between Binary and Decimal

C++ program to convert binary to decimal have been shown here.






1. C++ Program to convert binary to decimal

Code has been copied
/****************************************
    	  alphabetacoder.com
C++ program to convert binary to decimal
*****************************************/

#include <iostream>
#include <cmath>

using namespace std;

int main() {
    // declare variables
    long bin, num = 0;
    int r, i = 0;

    // take input
    cout << "Enter the number in binary: ";
    cin >> bin;

    // convert the number in decimal
    while (bin > 0) {
        r = bin % 10;
        num = num + r * pow(2, i);
        bin = bin / 10;
        i++;
    }

    // display the number in decimal
    cout << "Decimal: " << num << endl;

    return 0;
}

Output


Enter the number in binary: 10110

Decimal: 22





2. C++ Program to convert binary to decimal using recursion

Code has been copied
/*****************************
    alphabetacoder.com
C++ program to convert binary 
to decimal using recursion
******************************/

#include <iostream>

using namespace std;

// function to display
// binary to decimal
int binary_to_dcimal(long bin) {
    if (bin == 0)
        return 0;
    else
        return (bin % 10 + 2 * binary_to_dcimal(bin / 10));
}

int main() {
    // declare variables
    long bin;

    // take input
    cout << "Enter the number in binary: ";
    cin >> bin;

    // call function to display
    // the binary to decimal
    cout << "Decimal: " << binary_to_dcimal(bin) << endl;

    return 0;
}

Output


Enter the number in binary: 111111

Decimal: 63