Binary To Decimal Program In C
Implementation
Implementation of this algorithm is given below −
#include <stdio.h>
int string_length(char s[])
{
int i=0;
while(s[i]!='\0')
i++;
return i;
}
int binary2decimal(char n[])
{
int i,decimal,mul=0;
for(decimal=0,i=string_length(n)-1;i>=0;--i,++mul)
decimal+=(n[i]-48)*(1<<mul);
return decimal;
}
int main()
{
char n[] = "10101";
int decimal;
printf("Decimal equivalent of %s is : %d", n, binary2decimal(n));
return 0;
}
Output
Output of the program should be −
Decimal equivalent of 10101 is : 21
Advertisements