C++ Program to Convert Binary to Decimal

«
»

This is a C++ Program to Convert a Given Binary Number to its Decimal Equivalent.

Problem Description

The program converts a binary number to its decimal equivalent.

Problem Solution

1. The program takes a binary number.
2. Using a while loop, the remainders of the number are multiplied with powers of 2.
3. The decimal equivalent that is the result is printed.
4. Exit.

C++ Program/Source code

Here is the source code of C++ Program to Convert a Given Binary Number to its Decimal Equivalent. The program output is shown below.

  1. #include<iostream>
  2. using namespace std;
  3. int main ()
  4. {
  5.     int num, rem, temp, dec = 0, b = 1;
  6.     cout << "Enter the binary number : ";
  7.     cin >> num;
  8.     temp = num;
  9.     while (num > 0)
  10.     {
  11.         rem = temp % 10;
  12.         dec = dec + rem * b;
  13.         b *= 2;
  14.         temp /= 10;
  15.     }
  16.     cout << "The decimal equivalent of " << num << " is " << dec;
  17.     return 0;
  18. }
Program Explanation

1. The user is asked to enter a binary number and it is stored in the variable ‘num’.
2. The variable ‘b’ is initialized as 1 and ‘dec’ as 0. num is copied to the variable ‘temp’.
3. Using a while loop, modulus of temp is stored in ‘rem’.
4. rem is multiplied with b and added to dec.
5. In every iteration, b is multiplied with 2.
6. The loop continues till temp is less than 0.
7. The decimal equivalent is stored in dec and printed.

Note: Join free Sanfoundry classes at Telegram or Youtube
advertisement
advertisement
Runtime Test Cases
Case 1 :
Enter the binary number : 10
The decimal equivalent of 10 is 2
 
Case 2 :
Enter the binary number : 01010101
The decimal equivalent of 1010101 is 85
 
Case 3 :
Enter the binary number : 1111
The decimal equivalent of 1111 is 15

Sanfoundry Global Education & Learning Series – C++ Programs.

To practice all C++ programs, here is complete set of 1000+ C++ Programming examples.

Take C++ Programming Mock Tests - Chapterwise!
Start the Test Now: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & technical discussions at Telegram SanfoundryClasses.