C++ Program for Binary to decimal conversion

Program for Binary to decimal conversion

The concept of converting a binary number to a decimal number is very simple , extract the digits of the binary number (start from right for convenience )and multiply the digits with the proper base(power of 2) lastly add each of the results and we will get a converted number as an output.

Example: 10101

Decimal number = 1*(2^4)+ 0*(2^3) + 1*(2^2) + 0*(2^1) + 1*(2^0)=16 + 0 + 4 +0+1

        = 21

Program to Convert binary to decimal

Algorithm:-

  1. User gives an input(binary number)
  2. The input is stored in a long type variable say binary.
  3. A function convert()  is called with binary as parameter.
    1. Digits of binary are extracted one by one starting from right.

                     int rem = n%10;

                 2. Extracted digits are multiplied with proper base i.e. power of 2.

                     int res = rem*pow(2,i);

                  3. After multiplying each digit with proper base the results are added and stored in another variable say decimal.

                     decimal += res;

     4. The output is printed.

C++ Code:-

    
    //C++ Program
    //Convert binary to decimal
    #include <iostream>
    #include <math.h>
    using namespace std;
    //function to convert binary to decimal
    int convert(long n)
    {
        int i = 0,decimal0;
        //converting binary to decimal
        while (n!=0)
        {
            int rem = n%10;
            n /= 10;
            int res = rem * pow(2,i);
            decimal += res;
            i++;
        }
        return decimal;
    }
    //main program
    int main()
    {
        long binary;
        cout << “Enter binary number: “;
        cin >> binary;  
        cout << binary << ” in binary = “ << convert(binary<< ” in decimal”;
        return 0;
    }

    Output

    Enter binary number: 10110
    10110 in binary = 22 in decimal
coding (3)