To convert a binary number to decimal in a C program, you can use a simple algorithm that iterates through each digit of the binary number and accumulates the decimal value. Here's a detailed C program to convert a binary number to decimal with an example and output:
#include <stdio.h>
#include <math.h>
// Function to convert a binary number to decimal
int binaryToDecimal(long long binary) {
int decimal = 0, i = 0, remainder;
while (binary != 0) {
remainder = binary % 10;
binary /= 10;
decimal += remainder * pow(2, i);
++i;
}
return decimal;
}
int main() {
long long binary;
// Input binary number
printf("Enter a binary number: ");
scanf("%lld", &binary);
// Check if the input is a binary number
long long temp = binary;
int isBinary = 1;
while (temp != 0) {
int digit = temp % 10;
if (digit != 0 && digit != 1) {
isBinary = 0;
break;
}
temp /= 10;
}
if (isBinary) {
int decimal = binaryToDecimal(binary);
printf("Decimal equivalent: %d\n", decimal);
} else {
printf("Invalid input. Please enter a binary number (0s and 1s only).\n");
}
return 0;
}
Explanation:
We include the necessary header files,
stdio.h
for input/output functions andmath.h
for the power functionpow()
.We define a function
binaryToDecimal
that takes a binary number as input and converts it to a decimal number using a while loop.In the
main
function:- We ask the user to input a binary number.
- We check whether the input is a valid binary number by iterating through each digit and ensuring that it contains only 0s and 1s.
- If the input is a valid binary number, we call the
binaryToDecimal
function to convert it and then display the result as the decimal equivalent.
Example and Output:
Enter a binary number: 1010
Decimal equivalent: 10
In this example, the user entered the binary number 1010
, and the program correctly converted it to the decimal equivalent, which is 10
.