Home > Blockchain >  Binary to decimal converter in c logic error
Binary to decimal converter in c logic error

Time:11-28

I was trying to make a binary to decimal converter in c. But the out put that now comes is a random number. Before I that tried, it used to work for binary which consists of all 1s. eg when I enter 111 it used to give me 7. But when I entered 10 or 011 or anything else it gives me some random number. Now it gives me like it's a memory location. Please help. I tried with a online compiler.

 #include <stdio.h>
 #include<math.h>

 int main() {

int i=1, b[100];
char ch;
int decimal=0;
printf("enter binary\n");
ch=getchar();
while(ch!='\n'){
    ch=ch-'0';
    b[i]=ch;
    i  ;
    ch=getchar();
}
i=i-1;
while(i>=0){
    decimal=(b[i]*((int)pow(2,i)))   decimal;
    i--;
}
printf("%d",(int)decimal);
return 0;
}

CodePudding user response:

As comments pointed out probably initializing i as 0 would reduce complexity of working with i as index. Therefore there won't be a free b[0] in array. It would also help to produce powers of 2 by a for loop , most of the times using pow function may lead to some unwanted casting behavior especially when double type output is not wanted.

Try this method of summation :

for (int j=0 ; j<i ; j  ){
    decimal *=2 ;
    decimal  = b[j] ;
}

Also for getting binary number it would work out to ask user the length of number and then using scanf("%s",b) to avoid character by character input.

CodePudding user response:

The comments above suggest initializing i to 0 instead of 1. You definitely need to do that.

But you can also avoid the historical inaccuracies of the pow function by not using it and iterating over your array in the other direction. It enables you to stay in the integer space and avoid having to cast. Details here.

Instead of this:

while(i>=0){
    decimal=(b[i]*((int)pow(2,i)))   decimal;
    i--;
}

This:

for (int j = 0; j < i; j  ) {
    decimal = decimal * 2   b[j];
}
  • Related