c
  1. c-program-to-convert-binary-number-to-decimal-and-vice-versa

Program to Convert Binary Number to Decimal and vice-versa - (C Programs)

Example

Here is an example of converting a binary number to a decimal number using the C programming language:

#include <stdio.h>
#include <math.h>
 
int binaryToDecimal(long int binaryNum)
{
    int decimalNum = 0, i = 0, remainder;
    while (binaryNum != 0)
    {
        remainder = binaryNum % 10;
        binaryNum = binaryNum / 10;
        decimalNum += remainder*pow(2,i);
        ++i;
    }
    return decimalNum;
}
 
int main()
{
    long int binaryNum;
    printf("Enter a binary number: ");
    scanf("%ld", &binaryNum);
    printf("Decimal Number : %d\n", binaryToDecimal(binaryNum));
    return 0;
}

Output

The output of the above example code would be:

Enter a binary number: 1010
Decimal Number : 10

Explanation

This C program converts a binary number to a decimal number. It takes a binary number as an input from the user and uses a while loop to convert it to a decimal number. The remainder obtained by dividing the binary number by 10 is used to calculate the decimal equivalent of the current digit. The decimal equivalent is added to the running sum of the decimal number. The loop continues until the binary number becomes zero, at which point the final decimal number is returned.

Use

This program can be used to convert binary numbers to decimal numbers for various applications in computer science. Binary numbers are commonly used by digital devices and programs to represent and manipulate data. Decimal numbers, on the other hand, are typically used for human-readable output. Converting between binary and decimal numbers is therefore a fundamental operation in many computer programs.

Summary

In this C program, we have seen how to convert binary numbers to decimal numbers. This program can be used to perform this conversion for various applications in computer science. By using a loop and mathematical operations, we can easily convert between binary and decimal representations of numbers.

Published on: