Binary to Decimal Number Conversion

Binary to Decimal Number Conversion” is one of the classic programming problem exercise. Here, we are given a binary number, entered by user and our task is to write a program to  convert the given binary number to its equivalent decimal number.

Example:

INPUT:
Binary = 111
OUTPUT:
Decimal = 7
INPUT:
Binary = 100
OUTPUT:
Decimal = 4

To convert binary number into decimal, we will scan the number from right to left and put it into formula.

FORMULA TO CONVERT BINARY TO DECIMAL:
 2^0 * (last digit) + 2^1 * (second last digit) + ….

C++ Program to convert binary to decimal is as follows:

#include<bits/stdc++.h>  
using namespace std;  
long int convert(long int);  
int main()  
{  
    // Scan the binary number  
    long int binary;  
    cout<<"Enter the binary number : ";  
    cin>>binary;  
      
    //Call the convert function  
    long int decimal = convert(binary);  
      
    //Printing the decimal equivalent  
    cout<<"The decimal equivalent of "<<binary<<" is "<<decimal;  
}  
long int convert(long int binary)  
{  
    long int res = 0;  
    int i = 0;   
    while(binary > 0)  
    {  
        int digit = binary % 10; /* Extracting the last digit */  
        res = res + (digit * pow(2,i)); /* Putting it into formula */  
        binary =  binary/10;  
        i++;  
    }  
    return res;  
}  
OUTPUT: 
Enter the binary number : 111
The decimal equivalent of 111 is 7

Related Posts:

  1. Program to convert binary number to octal number.
  2. Program to convert binary number to hexadecimal number.
  3. Program to convert octal number to binary number.
  4. Program to convert octal number to decimal number.
  5. Program to convert octal number to hexadecimal number.
  6. Program to convert decimal number to binary number.
  7. Program to convert decimal number to octal number.
  8. Program to convert decimal number to hexadecimal number.
  9. Program to convert hexadecimal number to binary number.
  10. Program to convert hexadecimal number to octal number.
  11. Program to convert hexadecimal number to decimal number.
  12. Program to check Leap Year.
  13. Program to find largest amongst three numbers.
  14. Program to find factorial of a number.
  15. Program to find GCD of two numbers.
  16. Program to find LCM of two numbers.
  17. Program to check whether entered number is odd or even.
  18. Program to check whether entered number is prime number or not.
  19. Program to check whether entered number is palindrome or not.
  20. Program to check whether entered number is Armstrong Number or Not.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *