A Program to Convert Binary to Decimal

In this example, we are giving a program to convert a number from binary to decimal.


Program to convert binary to decimal:

  1. #include <iostream>
  2. #include <cmath>
  3. using namespace std;
  4. int convert(long long n);
  5. int main() {
  6. long long n;
  7. cout << "Enter a binary number: ";
  8. cin >> n;
  9. cout << n << " in binary = " << convert(n) << " in decimal " << endl;
  10. return 0;
  11. }
  12. int convert(long long n) {
  13. int dec = 0, i = 0, rem;
  14. while (n != 0) {
  15. rem = n % 10;
  16. n /= 10;
  17. dec += rem * pow(2, i);
  18. ++i;
  19. }
  20. return dec;
  21. }

Output:

Enter a binary number: 11011
11011 in binary = 27 in decimal