C program to convert binary to decimal

To convert a binary number to decimal in a C program, you can use a simple algorithm that iterates through each digit of the binary number and accumulates the decimal value. Here's a detailed C program to convert a binary number to decimal with an example and output:

#include <stdio.h>
#include <math.h>

// Function to convert a binary number to decimal
int binaryToDecimal(long long binary) {
    int decimal = 0, i = 0, remainder;
    
    while (binary != 0) {
        remainder = binary % 10;
        binary /= 10;
        decimal += remainder * pow(2, i);
        ++i;
    }
    
    return decimal;
}

int main() {
    long long binary;
    
    // Input binary number
    printf("Enter a binary number: ");
    scanf("%lld", &binary);
    
    // Check if the input is a binary number
    long long temp = binary;
    int isBinary = 1;
    while (temp != 0) {
        int digit = temp % 10;
        if (digit != 0 && digit != 1) {
            isBinary = 0;
            break;
        }
        temp /= 10;
    }
    
    if (isBinary) {
        int decimal = binaryToDecimal(binary);
        printf("Decimal equivalent: %d\n", decimal);
    } else {
        printf("Invalid input. Please enter a binary number (0s and 1s only).\n");
    }

    return 0;
}
 

Explanation:

  1. We include the necessary header files, stdio.h for input/output functions and math.h for the power function pow().

  2. We define a function binaryToDecimal that takes a binary number as input and converts it to a decimal number using a while loop.

  3. In the main function:

    • We ask the user to input a binary number.
    • We check whether the input is a valid binary number by iterating through each digit and ensuring that it contains only 0s and 1s.
    • If the input is a valid binary number, we call the binaryToDecimal function to convert it and then display the result as the decimal equivalent.

Example and Output:

Enter a binary number: 1010
Decimal equivalent: 10 

In this example, the user entered the binary number 1010, and the program correctly converted it to the decimal equivalent, which is 10.

Prasun Barua

Prasun Barua is an Engineer (Electrical & Electronic) and Member of the European Energy Centre (EEC). His first published book Green Planet is all about green technologies and science. His other published books are Solar PV System Design and Technology, Electricity from Renewable Energy, Tech Know Solar PV System, C Coding Practice, AI and Robotics Overview, Robotics and Artificial Intelligence, Know How Solar PV System, Know The Product, Solar PV Technology Overview, Home Appliances Overview, Tech Know Solar PV System, C Programming Practice, etc. These books are available at Google Books, Google Play, Amazon and other platforms.

*

Post a Comment (0)
Previous Post Next Post