How to convert binary number to decimal number in C++

2 Answers

0 votes
#include <iostream>

long BinaryToDecimal(long n);

int main()
{
	long binary = 11101111;

	std::cout << "The decimal number of is: " << BinaryToDecimal(binary) << std::endl;

	return 0;
}

long BinaryToDecimal(long n)
{
	int remainder;
	long decimal = 0, i = 0;

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


/*
run:

The decimal number of is: 239

*/

 



answered Jun 9, 2017 by avibootz
0 votes
#include <iostream>

long BinaryToDecimal(long long binary);

int main()
{
	long binary = 11101111;

	std::cout << "The decimal number of is: " << BinaryToDecimal(binary) << std::endl;

	return 0;
}

long BinaryToDecimal(long long binary)
{
	int decimal = 0, i = 0;

	while (binary != 0)
	{
		decimal += (binary % 10) * pow(2, i);
		i++;
		binary /= 10;
	}

	return decimal;
}

/*
run:

The decimal number of is: 239

*/

 



answered Jun 10, 2017 by avibootz
edited Jun 10, 2017 by avibootz

Related questions

1 answer 149 views
1 answer 148 views
2 answers 179 views
1 answer 131 views
131 views asked Aug 24, 2021 by avibootz
2 answers 281 views
281 views asked Aug 24, 2021 by avibootz
1 answer 220 views
1 answer 230 views
...