-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path40_bin2dec.c
More file actions
55 lines (49 loc) · 816 Bytes
/
40_bin2dec.c
File metadata and controls
55 lines (49 loc) · 816 Bytes
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
// Convert binary to decimal and vice-versa
#include<stdio.h>
unsigned long bin2dec(unsigned long bin);
unsigned long dec2bin(unsigned long dec);
unsigned long dec, bin;
int main(void)
{
int mod;
printf("Binary to Decimal: 1\nDecimal to Binary: 2\n");
scanf("%d", &mod);
if (mod == 1)
{
printf("Enter the binary number: ");
scanf("%lu", &bin);
bin2dec(bin);
}
else
{
printf("Enter the decimal number: ");
scanf("%lu", &dec);
dec2bin(dec);
}
return 0;
}
unsigned long bin2dec(unsigned long bin)
{
int a, exp=0;
while(bin != 0)
{
a = bin%10;
for (int i=0; i<exp;i++)
a*=2;
dec += a;
bin /= 10;
exp++;
}
printf("%lu\n",dec);
}
unsigned long dec2bin(unsigned long dec)
{
int a;
while(dec != 0)
{
a = dec%2;
bin = (bin*10) + a;
dec /= 2;
}
printf("%lu\n",bin);
}