Converting Binary using strings

I've written a program that asks the user to input a number using strings, the program then will convert that number to decimal, however Im having a problem with it, when I compile (using -lm) and run the a.out, lets say I try to convert 11 to decimal it gives a huge number... not sure where I went wrong so would anyone help please?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <stdio.h>
#include <string.h>
#include <math.h>

int main()
{

 char string[100];
 int s;
 char a;
 char j;
 int sum;

 printf("B = B to D\n");
 printf("D = D to B\n");
 printf("choose which one to convert to:");
 scanf("%c%c", &a, &j);

 if (a == 'B')
 {
        printf("enter binary number to convert to decimal: ");
        scanf("%s", string);

        for(s = strlen(string)-1; s >= 0; s--)
        {

                if(string[s] == '1')
                {
                sum = sum + pow(2,s);

                }
        }
 printf("the decimal number is: %d\n", sum);
 }

 return 0;
}
Last edited on
You did not initialize variable sum. Also I think that the right most bit should be powered starting from 0 not strlen( string ) - 1.
Last edited on
no he is doing correct.Just initialise sum=0

@Akshit

no he is doing correct.Just initialise sum=0


The right most digit is the less significant so it can not be equal to pow(2,s);
Last edited on
oh yeah sorry.I didn't looked up if condition
Topic archived. No new replies allowed.