C Program to Convert Binary Number to Decimal and vice-versa

This post explains the conversion of numbers from binary to decimal and vice versa, using the C programming language.

C Program to Convert Binary Number to Decimal and vice-versa

#include<stdio.h>
#include<math.h>
int convert(long long n);
int main()
{
    long long n;
    printf("Enter a binary number:");
    scanf("%lld",&n);
    printf("\n %lld in binary=%d in decimal", n,convert(n));
    return 0;
}
int convert(long long n)
{
    int deci=0,i=0,remi;
    while(n!=0)
    {
        remi=n%10;
        n/=10;
        deci+=remi*pow(2, i);
        ++i;
    }
    return deci;
}   

Output

Explanation

In this C program, we get to understand the conversion of binary numbers to decimal numbers. We initialize the function and start with the main function where we allow the user to enter the values required.

int convert(long long n);
int main()
{
    long long n;
    printf("Enter a binary number:");
    scanf("%lld",&n);
    printf("\n %lld in binary=%d in decimal", n,convert(n));
    return 0;
}

Then we call the function to do the conversion by using the while loop condition to get the desired output.

int convert(long long n)
{
    int deci=0,i=0,remi;
    while(n!=0)
    {
        remi=n%10;
        n/=10;
        deci+=remi*pow(2, i);
        ++i;
    }
    return deci;
}   

We now get the desired output.

%d