Binary to Decimal conversion program

This is a weekly challenge for OOP344.  This program converts a set of binary digits input by the user and converts it to its decimal value.

#include 
#include 
using namespace std;
#define NUMOFDIGITS 30

int getBinary(int x)
{
	int i; // for loop integer
	int power = 1; // power of 2 to calculate with each digit in x
	int dec_result = 0; // decimal result

	string s = to_string(x); // converts int x to string s
	int x_size = s.length(); // gets size of x

	// stores x into integer array
	int xarray[NUMOFDIGITS];
	for (i = 0; i  NUMOFDIGITS ? x_size = NUMOFDIGITS : x_size = x_size; // to allow only maximum number(NUMOFDIGITS) of digits.

	// Calculates decimal value
	for (i = x_size-1; i >= 0; i--)
	{
		dec_result += xarray[i] * power; // adds to dec_result starting at 1 * xarray[i], 2 * xarray[i], 4, 8, 16 etc..
		power *= 2; // increments power to double of power each time.  1, 2, 4, 8, 16, 32 etc..
	}

	return dec_result;
}

int main ()
{
	int x;

	cout  x;
	fflush(stdin);

	cout << "Decimal value is: " << getBinary(x) << endl;

	getchar();
	return 0;
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s