convert binary number to decimal number in c code example
Example 1: binary to decimal in c
#include <math.h>
#include <stdio.h>
int convert(long long n);
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;
}
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;
}
Example 2: binary to hexadecimal in c
#include <stdio.h>
int main()
{
long int binaryval, hexadecimalval = 0, i = 1, remainder;
printf("Enter the binary number: ");
scanf("%ld", &binaryval);
while (binaryval != 0)
{
remainder = binaryval % 10;
hexadecimalval = hexadecimalval + remainder * i;
i = i * 2;
binaryval = binaryval / 10;
}
printf("Equivalent hexadecimal value: %lX", hexadecimalval);
return 0;
}