In this post, we will learn how to convert binary to decimal using C Programming language.
![C Program To Convert Binary To Decimal](https://www.codingbroz.com/wp-content/uploads/2021/10/c-program-to-convert-binary-to-decimal-codingbroz.png)
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 != 0 | rem = n % 10 | num = num / 10 | temp | decimal += rem * pow(2, temp) |
---|---|---|---|---|
10010 != 0 | 10010 % 10 = 0 | 10010 / 10 = 1001 | 0 | 0 + 0 = 0 |
1001 != 0 | 1001 % 10 = 1 | 1001 / 10 = 100 | 1 | 0 + 2 = 2 |
100 != 0 | 100 % 10 = 0 | 100 / 10 =10 | 2 | 2 + 0 = 2 |
10 != 0 | 10 % 10 = 0 | 10 / 10 =1 | 3 | 2 + 0 = 2 |
1 != 0 | 1 / 10 = 1 | 1 / 10 | 4 | 2 + 16 = 18 |
0 != 0 | – | – | – | – |
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: