u

Sunday 3 June 2012

C++ Program to convert binary to decimal using a function

C++ Program to convert binary to decimal using a function


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

int binary[16] = {0};    //Store binary digits


//GET BINARY INPUT FROM USERS
void get_input(int binary[], int &counter)
{
    char digit[2] = {'\0'};    //Store single digits

    cout << "Enter binary number: ";

    //Take inputs until the user does not press enter key
    while( digit[0] != '\r' )
    {
        digit[0] = getche();

        //Store the digit to binary number only if it is not enter key
        if( digit[0] != '\r' )
        {
            binary[counter] = atoi(digit);
            counter++;
        }
    }
}


//CONVERT THE ENTERED BINARY NUMBER TO DECIMAL
void convert_BtoD(int binary[], int &counter)
{
    unsigned int decimal = 0;    //Stores the decimal equivalent
    double power = 0;        //The power to raise 2

    //Start with the last digit entered, move left and increase power
    for(int n=(counter-1); n>=0; n--)
    {
        decimal += (binary[n]*pow(2,power));
        power++;
    }
    cout << endl << decimal;
}


void main()
{
    int counter = 0;

    clrscr();
    get_input(binary, counter);
    convert_BtoD(binary, counter);
    cout<<endl;
    cout<<"Press any key to continue";
    getch();
}

0 comments:

Post a Comment

Share

Twitter Delicious Facebook Digg Stumbleupon Favorites More