mohamed benhaddou
mohamed benhaddou

Reputation: 27

how to fix this code (conversion binary to decimal with char in c)?

why this code don't work? (i want To convert a number from binary to decimal) there is a problem with pointer? or multiplication(char*int)

char cara[100];
char *t=cara;
int i=0;
int sum=0;
int j=0;
int m;

printf("entrer a binary number\n");
scanf("%s",&cara);
while(*t!="\0")
{
    j++;
    m=j-1;
}


for(i=0;i<j;i++)
{
    cara[i]=cara[i]*pow(2,m);
    m--;
}
int k;
for(k=0;k<j;k++)
{
    sum=sum+cara[i];
}
printf("%d",sum);
}

Upvotes: 0

Views: 1016

Answers (1)

4386427
4386427

Reputation: 44274

The first bug is here:

while(*t!="\0")

You have to use single quotes for characters - like while(*t!='\0'). To make it simpler you can just write while(*t).

Besides that problem also notice that you never update t. You need to add ++t; inside the loop.

The second bug is here:

cara[i]=cara[i]*pow(2,m);

Characters '0' and '1' do not have integer values zero and one so the calculation is wrong. The character '0' has integer value 48 and character '1' has integer value 49 (see https://da.wikipedia.org/wiki/ASCII) so the result will be completely wrong.

To get the calculation more correct you need:

cara[i] = (cara[i] - '0') * pow(2,m);

However, it is a bad idea to save these intermediate results back in a char. A char can't hold values higher than 127 (or 255 if char is unsigned) so you'll soon have an integer overflow.

In general there is no need for saving these intermediate result and there is no need for pow as you can simply multiply by 2 for each binary digit.

Try like this:

#include <stdio.h>

int main(void) {
    char *bin_str = "11001";
    unsigned result = 0;
    while (*bin_str)
    {
        result *= 2;
        result += *bin_str == '1' ? 1 : 0;
        ++bin_str;
    }
    printf("%d\n", result);
    return 0;
}

Upvotes: 2

Related Questions