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

In this example, you will learn to convert binary number to decimal and decimal number to binary manually by creating a user-defined function.
To understand this example, you should have the knowledge of following C programming topics:
  • C Programming Functions
  • C Programming User-defined functions
Visit this page to learn how to convert binary number to decimal. Read - Programming language

Example 1: Program to convert binary number to decimal

#include <stdio.h>
#include <math.h>
int convertBinaryToDecimal(long long n);

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

int convertBinaryToDecimal(long long n)
{
    int decimalNumber = 0, i = 0, remainder;
    while (n!=0)
    {
        remainder = n%10;
        n /= 10;
        decimalNumber += remainder*pow(2,i);
        ++i;
    }
    return decimalNumber;
}
Output
Enter a binary number: 110110111
110110111 in binary = 439
Visit this page to learn, how to convert decimal number to binary.

Example 2: Program to convert decimal number to binary

#include <stdio.h>
#include <math.h>
long long convertDecimalToBinary(int n);

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

long long convertDecimalToBinary(int n)
{
    long long binaryNumber = 0;
    int remainder, i = 1, step = 1;

    while (n!=0)
    {
        remainder = n%2;
        printf("Step %d: %d/2, Remainder = %d, Quotient = %d\n", step++, n, remainder, n/2);
        n /= 2;
        binaryNumber += remainder*i;
        i *= 10;
    }
    return binaryNumber;
}
Output
Enter a decimal number: 19
Step 1: 19/2, Remainder = 1, Quotient = 9
Step 2: 9/2, Remainder = 1, Quotient = 4
Step 3: 4/2, Remainder = 0, Quotient = 2
Step 4: 2/2, Remainder = 0, Quotient = 1
Step 5: 1/2, Remainder = 1, Quotient = 0
19 in decimal = 10011 in binary

Comments

Popular posts from this blog

C Program to Find the Sum of Natural Numbers using Recursion

C program to Reverse a Sentence Using Recursion

C program to calculate the power using recursion