-8

well this program is supposed to convert a binary number to decimal. im new to c and im not very confident in coding C. tried and coded this program but doesnt run properly. and I have no idea what part is wrong here. need some help to complete this program. thanks

binaryToDecimal(char str[]) {
    for(int i = strlen(str)-i; i>=0; i--) {
        if(str[i] == 48 || str[i] == 49) {
            int tmp = pow(2, counter);
            int sum= str[i]*tmp;
            counter++;
            answer += sum;
        } else if(str[i]>49 || str[i]<48) {
            printf("error");
        }
    }
    printf("%d", &answer);
}
Crowman
  • 25,242
  • 5
  • 48
  • 56
  • this may be of help: http://stackoverflow.com/questions/9852917/convert-binary-to-hex-to-decimal – jev Oct 05 '13 at 00:25
  • What's the type of answer? – LostBoy Oct 05 '13 at 00:25
  • 6
    Please explain *doesn't run properly*. What input do you give it? What output do you expect? What output did you actually get? – abelenky Oct 05 '13 at 00:26
  • "doesn't run properly" is not a problem description that is useful. What exactly does "doesn't run properly" mean? In what way is it not proper? If you want us to help you, you need to be *specific about the problem you're having*. After all, you know what it is, or you wouldn't be posting here for help. Why not explain it to us so we know too? – Ken White Oct 05 '13 at 00:30

3 Answers3

2

This phrase doesn't make sense:

int i = strlen(str)-i;

i hasn't been initialized yet, but you're using it in the expression!

I believe you meant:

int i = strlen(str)-1;   // ONE ... not I
abelenky
  • 63,815
  • 23
  • 109
  • 159
2

str[i] is a character, either '1' or '0' which as you have it is equal to 48 and 49 as integers. So you want to convert them to 1 and 0 them do the multiplication.

sum = (str[i] - 48) * tmp;
Musa
  • 96,336
  • 17
  • 118
  • 137
0

Assuming all variables have been initialised to sensible values and str holds the input. The following code should work, although it is not particularly efficient. You can use '0' and '1' instead of more obscure 48 and 49.

for (i = strlen(str)-1, j = 0; i >= 0; --i, ++j) { 

   if (str[i] != '0' && str[i] != '1') {
       printf("ERROR: unxepected input\n");
       exit(EXIT_FAILURE);
   }

   if (str[i] == '1')
       sum += pow(2, j);
}

when printing the result provide the value and not it's address, e.g.

printf("%d\n", sum);  // (!) not &sum
jev
  • 2,023
  • 1
  • 17
  • 26