I've made a small little program to convert binary numbers to decimal, but the problem is that I have to type each individual number one by one. Is there any way around this ?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#include<iostream>
#include<math.h>
usingnamespace std;
int main ()
{
int a[16],i,n,num=0;
cout<<"Type the no of bits of the binary number : ";
cin>>n;
for (i=0;i<n;i++)
{
cin>>a[i];
num+=(a[i]*pow(2,n-1-i));
}
cout<<"The binary representation is : ";
for (i=0;i<n;i++)
cout<<a[i]<<" ";
cout<<"\nThe decimal representation is : "<<num;
}
EDIT : I've replaced the integer array with characters, but I get a very large value when I try and convert it to decimal.
#include<iostream>
#include<math.h>
usingnamespace std;
int main ()
{
int i,n,num=0;
char a[16];
cout<<"Type the no of bits of the binary number : ";
cin>>n;
cin.ignore();
cout<<"Type the required number : ";
cin.getline(a,16);
for (i=0;i<n;i++)
{
num+=(a[i]*pow(2,n-1-i));
}
cout<<"The binary representation is : ";
for (i=0;i<n;i++)
cout<<a[i]<<" ";
cout<<"\nThe decimal representation is : "<<num;
}