Program to convert binary number to decimal and decimal to binary in C

Source Code

```// 37. Program to convert binary number to decimal and decimal to binary
// Arpan Das - CST 2nd Year (VOCLET)

#include <stdio.h>
//#include <conio.h>
#include <math.h>

int b2d(int);
int d2b(int);

int main () {
int num, ch;
//clrscr();

do {
printf("\n\t..:: convert binary number to decimal and vice-versa ::..\n\n");
printf("\n1. Decimal to Binary\n2. Binary to Decimal\n3. Exit\nPlease enter your choice: ");
scanf("%d", &ch);

if (ch == 1) {
printf("\nPlease enter a decimal number: ");
scanf("%d", &num);
printf("\nResult: %d", d2b(num));
} else if (ch == 2) {
printf("\nPlease enter a binary number: ");
scanf("%d", &num);
printf("\nResult: %d", b2d(num));
}
} while (ch >= 1 && ch <= 2);
return 0;
}

int d2b(int num) {
int r = 0, dig = 0; // result, digit

while (num != 0) {
r += (num%2) * (int)(pow(10.0, dig++) + 0.5);
num /= 2;
}

return r;
}

// 11001
// (1)*2^4 + (1)*2^3 + (0)*2^2 + (0)*2^1 + (1)*2^0
int b2d(int num) {
int dig = 0, r = 0;

while (num != 0) {
r += (num%2) * (int)(pow(2, dig++) + 0.5);
num /=10;
}

return r;
}
```

Output

``````	..:: convert binary number to decimal and vice-versa ::..

1. Decimal to Binary
2. Binary to Decimal
3. Exit

Please enter a decimal number: 14

Result: 1110
..:: convert binary number to decimal and vice-versa ::..

1. Decimal to Binary
2. Binary to Decimal
3. Exit