Binary to Decimal Converter in C
This program converts binary numbers to decimal numbers. Below is the C program along with an explanation of its structure and functionality.
Program Structure
The program is structured as follows:
- Include necessary libraries: The program includes the standard input-output library
#include <stdio.h>. - Function prototypes: Prototypes for the functions used in the program are declared.
- Main function: The main function handles user input and output, calling the appropriate functions to convert the binary number to a decimal number.
- Conversion function: A function that performs the actual conversion from binary to decimal.
C Program
#include <stdio.h>
// Function prototype for binary to decimal conversion
int binaryToDecimal(int binary);
int main() {
int binaryNumber;
// Prompt the user to enter a binary number
printf("Enter a binary number: ");
scanf("%d", &binaryNumber);
// Convert binary to decimal
int decimalNumber = binaryToDecimal(binaryNumber);
// Display the result
printf("The decimal equivalent of %d is %d\n", binaryNumber, decimalNumber);
return 0;
}
/**
* Function to convert a binary number to a decimal number
* @param binary The binary number to be converted
* @return The decimal equivalent of the binary number
*/
int binaryToDecimal(int binary) {
int decimal = 0, base = 1, remainder;
while (binary > 0) {
remainder = binary % 10;
decimal = decimal + remainder * base;
binary = binary / 10;
base = base * 2;
}
return decimal;
}
Explanation
Libraries: The program includes the standard input-output library #include <stdio.h> to enable input and output operations.
Function prototype: The prototype int binaryToDecimal(int binary); declares the function that will perform the conversion from binary to decimal.
Main function:
- The program starts by declaring an integer variable
binaryNumber. - It then prompts the user to enter a binary number using
printfand reads the input usingscanf. - The binary number entered by the user is passed to the
binaryToDecimalfunction, which returns the decimal equivalent. - Finally, the result is printed to the screen using
printf.
Conversion function:
- The function
binaryToDecimaltakes an integerbinaryas an argument and initializes three variables:decimal(to store the result),base(to keep track of the power of 2), andremainder(to store the remainder when the binary number is divided by 10). - The function uses a
whileloop to iterate through each digit of the binary number. Inside the loop:- The remainder when the binary number is divided by 10 is calculated and stored in
remainder. - This remainder is then multiplied by the current base (power of 2) and added to
decimal. - The binary number is divided by 10 to remove the last digit, and
baseis multiplied by 2 to move to the next power of 2.
- The remainder when the binary number is divided by 10 is calculated and stored in
- Once the loop completes, the function returns the decimal equivalent.
