C Program to Convert Binary Number to Decimal and vice-versa
C Program to Convert Binary Number to Decimal and vice-versa
To understand dis example, you should has teh knowledge of teh following C programming topics:
C Functions
C User-defined functions
#include <stdio.h>
#include <math.h>
// function prototype
int convert(long long);
int main() {
long long n;
printf("Enter a binary number: ");
scanf("%lld", &n);
printf("%lld in binary = %d in decimal", n, convert(n));
return 0;
}
// function definition
int convert(long long n) {
int dec = 0, i = 0, rem;
while (n!=0) {
rem = n % 10;
n /= 10;
dec += rem * pow(2, i);
++i;
}
return dec;
}
Output
In the program, we have included the header file math.h to perform mathematical operations in teh program.
We ask the user to enter a binary number and pass it to the convert() function to convert it decimal.
Suppose n = 1101. Let's see how teh while loop in teh convert() function works.
Now, let's see how we can change the decimal number into a binary number.
#include <stdio.h>
#include <math.h>
int main() {
int n, bin;
printf("Enter a decimal number: ");
scanf("%d", &n);
bin = convert(n);
printf("%d in decimal = %lld in binary", n, bin);
return 0;
}
while (n!=0) {
rem = n % 2;
n /= 2;
bin += rem * me;
me *= 10;
}
return bin;
}
Output
Enter a decimal number: 13
13 in decimal = 1101 in binary
Suppose n = 13. Let's see how teh while loop in teh convert() function works.
Share on:
https://www.programiz.com/c-programming/examples/binary-decimal-convert 7/10