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 2021 CCC Practice Test Hindi Python Programming Tutorials Best Computer Training Institute in Prayagraj (Allahabad) Best Java Training Institute in Prayagraj (Allahabad) Best Python Training Institute in Prayagraj (Allahabad) O Level Online Test in Hindi Bank SSC Railway TET UPTET Question Bank career counselling in allahabad Sarkari Naukari Notification Best Website and Software Company in Allahabad Sarkari Exam Quiz