Created
August 11, 2017 12:17
-
-
Save snadahalli/d67b0d3858c5c4238e39292e8b970b91 to your computer and use it in GitHub Desktop.
Binary to Decimal C Program
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<stdio.h> | |
/* | |
* Function to convert a given binary number to | |
* its decimal equivalent. | |
*/ | |
int binary_to_decimal(int num) { | |
int rem, base = 1, decimal_number = 0; | |
while( num > 0) { | |
rem = num % 10; | |
if((rem == 0) || (rem == 1)) { | |
decimal_number = decimal_number + rem * base; | |
num = num / 10 ; | |
base = base * 2; | |
} else { | |
return -1; // Invalid binary number | |
} | |
} | |
return decimal_number; | |
} | |
int main() { | |
long int binary_number, decimal_number; | |
printf("Enter any binary number : "); | |
scanf("%ld", &binary_number); | |
decimal_number = binary_to_decimal(binary_number); | |
if(decimal_number != -1) { | |
printf("The decimal equivalent value of binary %ld is: %ld", | |
binary_number, decimal_number); | |
} else { | |
printf("\nPlease enter a valid binary number!"); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thnx