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 (Binary to Decimal Number Conversion):
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 FOR BINARY TO DECIMAL NUMBER CONVERSION: 2^0 * (last digit) + 2^1 * (second last digit) + ….
C++ Program for binary to decimal number conversion is as follows:
/* C++ Program for binary to decimal number conversion */
#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:
- Program to convert binary number to hexadecimal number.
- Program to convert octal number to binary number.
- Program to convert octal number to decimal number.
- Program to convert octal number to hexadecimal number.
- Program to convert decimal number to binary number.
- Program to convert decimal number to octal number.
- Program to convert decimal number to hexadecimal number.
- Program to convert hexadecimal number to binary number.
- Program to convert hexadecimal number to octal number.
- Program to convert hexadecimal number to decimal number.
- Program to find sum of first ‘n’ natural numbers.
- Program to Reverse a Number.
- Program to swap two Numbers.
- Program to print Fibonacci Series up to Nth Term.
- Program to find and print nth Fibonacci number.
- Program to find Power of the Number.
- Program to find Quotient and Remainder.
- Program to find largest amongst three numbers.
- Program to find factorial of a number.
- Program to find GCD of two numbers.