fastread homefastrread library fastread menu

C : Convert Binary Number to Decimal and vice-versa

Tutorial by:Manisha Dubey      Date: 2016-06-17 03:53:44

❰ Previous Next ❱


In this example, you will learn to convert binary number to decimal and decimal number to binary manually by creating a user-defined function

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

 

 

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;

    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

❰ Previous Next ❱


C

Submit Your Thought, Tutorial, Articls etc.

Submit Your Information India's Number one online promotion website