C Program To Convert Binary To Decimal

In this post, we will learn how to convert binary to decimal using C Programming language.

C Program To Convert Binary To Decimal

Here in this program, we take a binary number as input and convert it into a decimal number using a user-defined function.

So, without further ado, let’s begin this tutorial.

C Program To Convert Binary To Decimal

// C Program To Convert Binary To Decimal 
#include <stdio.h>
#include <math.h>
int binarytodecimal(long num){
    int rem, temp = 0, decimal = 0;
    while (num != 0){
        rem = num % 10;
        num = num / 10;
        decimal = decimal + rem * pow(2, temp);
        temp++;
    }
    return decimal;
}

int main(){
    long num;
    
    // Asking for Input
    printf("Enter a number: ");
    scanf("%ld", &num);
    
    printf("Equivalent decimal number is: %d", binarytodecimal(num));
    return 0;
}

Output

Enter a number: 10010
Equivalent decimal number is: 18

How Does This Program Work ?

int binarytodecimal(long num){
    int rem, temp = 0, decimal = 0;
    while (num != 0){
        rem = num % 10;
        num = num / 10;
        decimal = decimal + rem * pow(2, temp);
        temp++;
    }
    return decimal;
}

In this program, we have defined a custom function named binarytodecimal which will convert the binary number into decimal number.

Suppose the user enters 10010, then we get the following result:

num != 0rem = n % 10num = num / 10tempdecimal += rem * pow(2, temp)
10010 != 010010 % 10 = 010010 / 10 = 100100 + 0 = 0
1001 != 0 1001 % 10 = 1  1001 / 10 = 10010 + 2 = 2
100 != 0  100 % 10 = 0100 / 10 =10 22 + 0 = 2
10 != 0  10 % 10 = 0 10 / 10 =132 + 0 = 2
1 != 01 / 10 = 11 / 1042 + 16 = 18
0 != 0 
Binary To Decimal

Hence, we get (10010)2 = (18)10

    printf("Equivalent decimal number is: %d", binarytodecimal(num));

We call our custom function binarytodecimal in the main() function which will display the result to the user.

Conclusion

I hope after going through this post, you understand how to convert binary to decimal using C Programming language.

If you have any doubt regarding the program, feel free to contact us in the comment section. We will be delighted to help you.

Also Read:

Leave a Comment

Your email address will not be published. Required fields are marked *