Binary to Decimal Converter
July 27, 2009 Leave a comment
A binary number is a sequence of bits (binary digits – 0’s and 1’s) of the form BnBn-1……B1 B0, where each Bi is a bit. The decimal equivalent is calculated by Bn * 2n+ Bn-1 * 2n-1 + … + B1 * 2 + B0. Write a program to input a binary number and output the decimal equivalent. The sample input will not have more than 8 individual bits (i.e., the largest value to be entered is 11111111).
Example 1:
Enter binary number: 101
In decimal: 5
Example 2:
Enter binary number: 11111
In decimal: 31
Solutions:
#include <stdio.h>
#include <string.h>
#include <math.h>
int main ()
{
char a [9];
printf ("Enter binary number: ");
scanf ("%s", a);
int length = strlen (a) - 1;
int decimal = 0;
for ( int i = length; i >= 0; i-- )
decimal = decimal + (( a [i] - '0' ) * (int) pow ( 2, length - i ));
printf ( "In decimal: %d\n", decimal );
return 0;
}

