English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C Language Basic Tutorial

C Language Flow Control

C Language Functions

C Language Arrays

C Language Pointers

C Language Strings

C Language Structure

C Language File

C Others

C Language Reference Manual

C program to convert binary to decimal and vice versa

Comprehensive Collection of C Programming Examples

In this example, you will learn how to convert binary numbers to decimal and vice versa by creating user-defined functions.

To understand this example, you should be familiar with the followingC programming languageTopic:

Program to convert binary to decimal

#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(binary) = %d(decimal)", n, convert(n));
    return 0;
}
int convert(long long n) {
    int dec = 0, i = 0, rem;
    while (n != 0) {
         10;
        n /= 10;
        dec += rem * pow(2, i);
        ++i;
    }
    return dec;
}

Output Result

Enter a binary number: 110110111
110110111(Binary)= 439(Decimal)

Program to convert decimal to binary

#include <math.h>
#include <stdio.h>
long long convert(int n);
int main() {
    int n;
    printf("Enter a decimal number: ");
    scanf("%d", &n);
    printf("%d(decimal) = %lld(binary)", n, convert(n));
    return 0;
}
long long convert(int n) {
    long long bin = 0;
    int rem, i = 1, step = 1;
    while (n != 0) {
         2;
        printf("Step %d: %d",/2The remainder = %d, the quotient = %d\n++, n, rem, n / 2);
        n /= 2;
        bin += rem * i;
        i *= 10;
    }
    return bin;
}

Output Result

Enter a Decimal Number: 29
Step 1: 29/2, Remainder = 1, Quotient = 14
Step 2: 14/2, Remainder = 0, Quotient = 7
Step 3: 7/2, Remainder = 1, Quotient = 3
Step 4: 3/2, Remainder = 1, Quotient = 1
Step 5: 1/2, Remainder = 1, Quotient = 0
29(Decimal) = 11101(Binary)

Comprehensive Collection of C Programming Examples