Google News
logo
C Program to Convert Binary Number to Decimal Number
In the following example of C program that converts a binary number to a decimal number :
Program :
#include <stdio.h>
#include <math.h>

int main() {
    int binary, decimal = 0, power = 0;
    printf("Enter a binary number: ");
    scanf("%d", &binary);

    while (binary != 0) {
        int digit = binary % 10;
        decimal += digit * pow(2, power);
        binary /= 10;
        power++;
    }

    printf("The decimal equivalent is %d\n", decimal);
    return 0;
}
Output :
Enter a binary number: 1010101
The decimal equivalent is 85
Explanation :

* We start by declaring three variables : binary to store the binary number, decimal to store the decimal equivalent, and power to keep track of the current power of 2.

* We ask the user to enter a binary number using printf and scanf.

* We use a while loop to convert each digit of the binary number to decimal. The loop continues until the binary number becomes 0.

* Inside the loop, we get the rightmost digit of the binary number using the modulo operator %, and then multiply it with 2 raised to the current power of 2 using the pow function from the math library. We add this value to the decimal variable.

* We then divide the binary number by 10 to remove the rightmost digit, and increment the power variable by 1 to move to the next digit.

* After the loop, we print the decimal variable as the decimal equivalent using printf.

Note : This program assumes that the input binary number is valid (i.e., it only contains 0s and 1s). If the input is invalid, the program may produce unexpected results.