C++ for Beginners: C++ Program to Convert Binary Number to Decimal and vice-versa

(C++ programming Example for Beginners)

C++ Program to Convert Binary Number to Decimal and vice-versa

In this example, you will learn to convert binary number to decimal, and decimal number to binary manually by creating user-defined functions.


Example 1: C++ Program to convert binary number to decimal


#include <iostream>
#include <cmath>

using namespace std;

int convertBinaryToDecimal(long long);

int main(){
    long long n;

    cout << "Enter a binary number: ";
    cin >> n;
 
    cout << n << " in binary = " << convertBinaryToDecimal(n) << "in decimal";
    return 0;
}

int convertBinaryToDecimal(long long n){
    int decimalNumber = 0, i = 0, remainder;
    while (n!=0)
    {
        remainder = n%10;
        n /= 10;
        decimalNumber += remainder*pow(2,i);
        ++i;
    }
    return decimalNumber;
}

Output

Enter a binary number: 1111
1111 in binary = 15

Example 2: C++ Program to convert decimal number to binary


#include <iostream>
#include <cmath>
using namespace std;

long long convertDecimalToBinary(int);

int main(){
    int n, binaryNumber;

    cout << "Enter a decimal number: ";
    cin >> n;
    binaryNumber = convertDecimalToBinary(n);
    cout << n << " in decimal = " << binaryNumber << " in binary" << endl ;
    return 0;
}

long long convertDecimalToBinary(int n){
    long long binaryNumber = 0;
    int remainder, i = 1, step = 1;

    while (n!=0)
    {
        remainder = n%2;
        cout << "Step " << step++ << ": " << n << "/2, Remainder = " << remainder << ", Quotient = " << n/2 << endl;
        n /= 2;
        binaryNumber += remainder*i;
        i *= 10;
    }
    return binaryNumber;
}

Output

Enter a decimal number: 19
Step 1: 19/2, Remainder = 1, Quotient = 9
Step 2: 9/2, Remainder = 1, Quotient = 4
Step 3: 4/2, Remainder = 0, Quotient = 2
Step 4: 2/2, Remainder = 0, Quotient = 1
Step 5: 1/2, Remainder = 1, Quotient = 0
19 in decimal = 10011 in binary

 

C++ for Beginners: C++ Program to Convert Binary Number to Decimal and vice-versa

Sign up to get end-to-end “Learn By Coding” example.



Disclaimer: The information and code presented within this recipe/tutorial is only for educational and coaching purposes for beginners and developers. Anyone can practice and apply the recipe/tutorial presented here, but the reader is taking full responsibility for his/her actions. The author (content curator) of this recipe (code / program) has made every effort to ensure the accuracy of the information was correct at time of publication. The author (content curator) does not assume and hereby disclaims any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from accident, negligence, or any other cause. The information presented here could also be found in public knowledge domains.