Using - C
#include<stdio.h>
#include<math.h>
#include<string.h>
void convertToDecimal(char binary[ ]);
void main() {
int i;
char binary[1024];
printf("Enter binary number: ");
gets(binary);
printf("BINARY : %s",binary);
convertToDecimal(binary);
}
void convertToDecimal(char binary[ ]) {
int i, eqv_decimal = 0, length = strlen(binary);
strrev(binary);
for(i=0; i < length; i++) {
if(binary[i]=='1') {
eqv_decimal += pow(2,i);
}
}
printf("\nDECIMAL: %d", eqv_decimal);
}
OUTPUT
Enter binary number: 101
BINARY : 101
DECIMAL: 5
Using - C++
#include<iostream>
#include<math.h>
#include<string.h>
#include<algorithm>
using namespace std;
void convertToDecimal(string binary);
int main() {
string binary;
cout<< "Enter binary number: ";
getline(cin,binary);
cout<<"BINARY : "<< binary;
convertToDecimal(binary);
return 0;
}
void convertToDecimal(string binary) {
int eqv_decimal = 0, length = binary.length();
reverse(binary.begin(), binary.end());
for(int i=0; i < length; i++) {
if(binary[i]=='1') {
eqv_decimal += pow(2,i);
}
}
cout<< "\nDECIMAL: "<< eqv_decimal;
}
OUTPUT
Enter binary number: 101110
BINARY : 101110
DECIMAL: 46