-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbinary to decimal.cpp
67 lines (66 loc) · 1.4 KB
/
binary to decimal.cpp
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
56
57
58
59
60
61
62
63
64
65
66
67
#include<iostream>
#include<math.h>
long binary_to_decimal(long binary)
{
long num,decimal = 0,digit;
int n=0;
num=binary;
while(num!=0)
{
digit=num%10;
if(digit==1)
{
decimal=decimal+pow(2,n);
}
n++;
/*removing last digit*/
num=num/10;
}
return decimal;
}
using namespace std;
long decimal_to_binary(long decimal)
{
long dec, binary;
int rem, place = 1;
binary = 0;
/*Passing decimal to dec variable*/
dec = decimal;
while(dec > 0)
{
rem = dec % 2;
binary = (rem * place) + binary;
dec =dec/2;
place =place*10;
}
return binary;
}
int main()
{
long binary,decimal,deci,bin;
int a;
cout<<"To convert Binary to Decimal Enter 1"<<endl;
cout<<"To convert Decimal To Binary Enter 2"<<endl;
cin>>a;
switch(a)
{
case 1:
cout<<"Enter binary number\n";
cin>>binary;
deci = binary_to_decimal(binary);
cout<<"Binary Number :"<< binary << endl;
cout<<"Decimal Number :"<< deci << endl;
break;
case 2:
cout<<"Enter any decimal number:\n";
cin>>decimal;
bin = decimal_to_binary(decimal);
cout<<"Decimal number :"<< decimal<< endl;
cout<<"Binary number :"<< bin<< endl;
break;
default:
cout<<"Enter a Valid Choice"<<endl;
break;
}
return 0;
}