Sem 5‎ > ‎DCCN LAB‎ > ‎

P-0b WAP to convert Binary to Decimal

posted Nov 6, 2012, 12:40 AM by Neil Mathew

SOURCE CODE:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include <iostream>
 
using namespace std;
 
int pow(int n, int i)
{
int result=1;
 
while(i--)
{
result*=n;
}
 
return result;
}
 
 
int main()
{
  int n;
 
  cout<<"Enter A Binary Number: ";
  cin>>n;
 
  cout<<"\n BINARY: "<<n;
 
        // 128 = 2^7 = 8 bit
        //  64 = 2^6 = 7 bit
        //  32 = 2^5 = 6 bit
        //  16 = 2^4 = 5 bit
        //  08 = 2^3 = 4 bit
        //  04 = 2^2 = 3 bit
        //  02 = 2^1 = 2 bit
        //  01 = 2^0 = 1 bit
 
        int i=0; //1st place
        int dec=0;
        int digit;
        
        do
        {
        digit = n%10;
        
        if( digit == 1 )
        dec+=pow(2,i);
 
        i++;
        n/=10;
        }
        while (n > 0);
        
 
  cout<<"\n DECIMAL: "<<dec<<endl;
        return 1;
}

OUTPUT:


Enter A Binary Number: 
 BINARY: 1100
 DECIMAL: 12

Comments