Converting unsigned Binary numbers to decimal

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>
using namespace 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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include<iostream>
#include<math.h>
using namespace 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;
}
Last edited on
closed account (D80DSL3A)
The integer values for a[i] are much higher than 1 or 0.
Try instead for line 15:
if( a[i] == '1' ) num+=pow(2,n-1-i);

EDIT: You can eliminate usage of the pow function by processing the bits from low to high order instead:
1
2
3
4
5
6
int twoPow = 1;
for (i=n-1;i>=0;i--)
{
      if( a[i] == '1' ) num+=twoPow;
      twoPow *= 2;
}
Last edited on
Yep, That did it for me. This code works. Thank you very much :D
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include<iostream>
#include<string.h>
#include<stdio.h>
using namespace std;
int main ()
{
       int i,n,num=0;
       char a[16];
       cout<<"Type the required number : ";
       gets(a);
       n=strlen(a);
       int twoPow = 1;
       for (i=n-1;i>=0;i--)
       {
                if( a[i] == '1' ) num+=twoPow;
                      twoPow *= 2;
       }
       cout<<"The binary representation is : ";
       for (i=0;i<n;i++)
               cout<<a[i]<<" ";
        cout<<"\nThe decimal representation is : "<<num;
}
Last edited on
Topic archived. No new replies allowed.