C PROGRAMMING

write a c program to convert a given number into binary and a binary number to decimal

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

int convert(long n);
long convert_decimal_to_binary(int n);
main()
{
int dec;
long n;
printf("Enter a binary number: ");
scanf("%lld", &n);
printf("%lld in binary = %d in decimaln", n, convert_binary_to_decimal(n));
dec=convert_binary_to_decimal(n);
printf("%d in decimal = %lld in binaryn", dec, convert_decimal_to_binary(dec));

}

int convert_binary_to_decimal(long n)
{
int dec = 0, i = 0, rem;
while (n != 0)
{
rem = n % 10;
n /= 10;
dec += rem * pow(2, i);
++i;
}
return dec;
}
long convert_decimal_to_binary(int n)
{
long long bin = 0;
int rem, i = 1;
while (n != 0)
{
rem = n % 2;
n /= 2;
bin += rem * i;
i *= 10;
}
return bin;
}

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button