954,480 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Binary To Decimal Conversion in C

I've been trying to display the equivalent decimal number of the input binary number. I tried the below piece of code but am not achieving the result. I don't seem to understand why?
Please Help!!

#include<stdio.h>
#include<conio.h>
#include<math.h>
int a=0;
int main()
{
    char bin[8];
    int i=0,len=0,r=0,w;
    printf("Enter a Binary Number :: ");
    scanf("%s",bin);
    printf("\n");
    len = strlen(bin);
    for(i=0;i<len;i++)
    {
            w=pow(2,i);
            r+=bin[i]*w;
    }     
    printf("Decimal is :: %d\n\n",r);
    scanf("%d",&a);
    getch();
    return 0;
}
guru_iyer
Light Poster
30 posts since Aug 2010
Reputation Points: 10
Solved Threads: 0
 

Try this code:

for(i = 0; i < len; i++)
    {
        r = r * 2 + (bin[i] == '1' ? 1 : 0);
    }


or

for(i = 0; i < len; i++)
    {
        r = r * 2 + (bin[i] - (int)'0');
    }
volvo877
Newbie Poster
7 posts since Jun 2009
Reputation Points: 3
Solved Threads: 3
 

ya the first one worked.. can you explain the logic please?

guru_iyer
Light Poster
30 posts since Aug 2010
Reputation Points: 10
Solved Threads: 0
 
can you explain the logic please?

The logic is very simple and explained here:
Convert from Binary to Decimal (Doubling method)

volvo877
Newbie Poster
7 posts since Jun 2009
Reputation Points: 3
Solved Threads: 3
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: