Convert Binary to Decimal and Vice Versa in C using Function
ADVERTISEMENTS
Convert binary to decimal and vice versa in C using function. In this article, you will learn how to convert binary to decimal and vice versa in c using function.
Convert Binary to Decimal in C
// Convert Binary to Decimal in C using Function
#include <stdio.h>
#include <math.h>
int convert(long long x);
// It's the driver function
int main() {
long long x;
printf("-----Enter a binary number to convert-----\n");
scanf("%lld", &x);
printf("\nThe Binary: %lld => Decimal: %d\n", x, convert(x));
return 0;
}
// This function will convert number binary to decimal
int convert(long long x) {
int dec = 0, i = 0, rem;
while (x != 0) {
rem = x % 10;
x /= 10;
dec += rem * pow(2, i);
++i;
}
return dec;
}
Output
-----Enter a binary number to convert-----
1010000
The Binary: 1010000 => Decimal: 80
Convert Decimal to Binary in C
// Convert Decimal to Binary in C using Function
#include <stdio.h>
long long convert(int x);
// It's the driver function
int main() {
int x;
printf("-----Enter a decimal number to convert-----\n");
scanf("%d", &x);
printf("\nThe Decimal: %d => Binary: %lld\n", x, convert(x));
return 0;
}
// This function will convert number decimal to binary
long long convert(int x) {
long long bin = 0;
int rem, i = 1, step = 1;
while (x != 0) {
rem = x % 2;
x /= 2;
bin += rem * i;
i *= 10;
}
return bin;
}
Output
-----Enter a decimal number to convert-----
80
The Decimal: 80 => Binary: 1010000