Change from binary base to decimal base

0

I've been trying to program a code to solve an exercise. Here's the question:

Write a program in language C that reads a string of any size containing binary digits and prints the corresponding decimal value on the screen.

The input reading should be done character by character using the getchar () function.

However, after creating a code that I thought was more complex for the program, I noticed a problem that I can not solve. The Code:

#include <stdio.h>

int main()

{
char c;
unsigned int dec=0, i=1;

do
{

    c = getchar();  

    if ( c -'0'== 1)
    {
        dec+= i;
    }

    i*=2;

}
while(c != '\n');

printf("%d\n", dec);

return 0;
} 

The problem is that the code is reading the number and creating a left-handed polynomial - > right, and base change polynomials are read in the opposite direction. Due to the use of getchar() I do not know how to end the exercise. Can anyone solve this problem?

    
asked by anonymous 29.11.2018 / 21:52

1 answer

1

The logic that has works, but reading from the bit of lower weight to the one of greater weight. Which means you have to enter the bits in contrast to what would be normal.

In order to solve this particular problem and keeping the logic it has, you can first save the bits in an array, and then go through that array in the reverse direction, applying the same operations.

Example:

#include <stdio.h>

int main() {
    char c;
    unsigned int dec = 0, i = 1;

    char bits[32];
    int bit_corrente = 0;
    while ((c = getchar()) != '\n') { //este while so guarda os bits
        bits[bit_corrente++] = c - '0';
    }

    int j;
    for (j = bit_corrente - 1;j >= 0; --j){ //agora percorre os bits na ordem inversa
        if (bits[j] == 1){
            dec += i;
        }
        i *= 2;
    }

    printf("%d\n", dec);
    return 0;
}

See on Ideone

It's interesting to mention that there are many ways to do the same conversion, but this one is most similar to the logic you already had in the code.

    
30.11.2018 / 16:55