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;
}

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');
    }

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.