#include <stdio.h>
#include <string.h>
#include <math.h>
// Function to convert binary to decimal
int binaryToDecimal(const char *binary) {
int decimal = 0; // Variable to store the decimal result
int length = strlen(binary); // Get the length of the binary string
// Loop through each character in the binary string
for (int i = 0; i < length; i++) {
// Get the bit value (0 or 1) by converting character to integer
int bit = binary[length - 1 - i] - '0';
// Add the decimal value of the current bit
decimal += bit * pow(2, i);
}
return decimal; // Return the computed decimal value
}
int main() {
char binary[65]; // Array to hold binary input (up to 64 bits + null terminator)
printf("Enter a binary number: ");
scanf("%64s", binary); // Read the binary input (up to 64 characters)
int decimal = binaryToDecimal(binary); // Call the conversion function
printf("Decimal equivalent: %d\n", decimal); // Print the result
return 0; // Indicate successful completion
}
Explanation:
Binary Representation:
In binary, each digit represents a power of 2. For example, in the binary number 1011:
This means that each bit contributes a specific value based on its position.
Decimal Representation:
The decimal system uses ten digits (0-9), and each digit’s position represents a power of 10.
Program Structure
Includes and Libraries:
The program begins by including necessary libraries:
stdio.h for standard input and output.
string.h for string manipulation functions.
math.h for mathematical functions like powers.
Function Definition:
A function called binaryToDecimal is defined to perform the conversion. It takes a string input representing a binary number and processes it to compute the decimal value.
Input Handling:
The main function prompts the user to enter a binary number, reads the input, and stores it in a character array.
Conversion Logic:
The function calculates the decimal value by iterating through each character of the binary string:
It accesses each bit from right to left, converts it from a character to an integer, and computes its contribution to the decimal total based on its position.
This is done using the formula bit×2positionbit \times 2^{position}bit×2position.
Output:
Once the conversion is complete, the program prints the decimal equivalent of the entered binary number.
Output
Enter a binary number: 1011
Decimal equivalent: 11