- To convert binary number into decimal
User Input: In Binary : 100
Output: In decimal : 4
#include <iostream>
#include <math.h>
using namespace std;
int toDecimal(long long num) {
int n=0,i=0;
while(num!=0) {
if(num%10==0 || num%10==1) {
n=n+pow(2,i++)*(num%10);
}
else {
cout<<"Number is not in binary form \n";
return 0;
}
num/=10;
}
return n;
}
int main() {
long long num;
int count=0;
cout<<"Enter Your binary number : ";
cin>>num;
cout<<"Number in decimal : "<<toDecimal(num);
return 0;
}
Enter Your binary number : 1101 Number in decimal : 13Program
Binary Numbers : Numbers with only 0 & 1 combination
Examples like: 101, 111, 10, 11111
Main Logic :
int toDecimal(long long num) {
int n=0,i=0;
while(num!=0) {
if(num%10==0 || num%10==1) { // checking for binary
n=n+pow(2,i++)*(num%10); // converting to decimal
}
else {
cout<<"Number is not in binary form \n";
return 0;
}
num/=10;
}
return n;
}
Calculation: Lets take binary number n=100 = 20*0 + 21*0 + 22*1 = 0 + 0 + 4 = 4 ------------------------------------------------------------------------ take every single digit of your binary number from right side and multiply it with 2 to the power of index position starting form 0 at the right side Index position 2 1 0 | | | Binary Number 1 0 0Concept
Coming Soon !
QuickIn order to succeed you must fail, so that you know what not to do the next time.