C++ Program to Convert the given Binary number 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.

advertisement
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.

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.

advertisement

advertisement
advertisement
advertisement
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He is Linux Kernel Developer & SAN Architect and is passionate about competency developments in these areas. He lives in Bangalore and delivers focused training sessions to IT professionals in Linux Kernel, Linux Debugging, Linux Device Drivers, Linux Networking, Linux Storage, Advanced C Programming, SAN Storage Technologies, SCSI Internals & Storage Protocols such as iSCSI & Fiber Channel. Stay connected with him @ LinkedIn