Programming Examples

C Program to Convert Binary Number to Decimal and vice versa


Write a C Program to Convert Binary Number to Decimal and vice versa

Solution

#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;
}
Output

Enter a binary number: 110110111

110110111 in binary = 439

CCC Online Test Python Programming Tutorials Best Computer Training Institute in Prayagraj (Allahabad) Online Exam Quiz O Level NIELIT Study material and Quiz Bank SSC Railway TET UPTET Question Bank career counselling in allahabad Best Website and Software Company in Allahabad Website development Company in Allahabad