Change of binary basis to decimal basis

Asked

Viewed 108 times

0

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

Write a program in C language that reads a string of any size containing binary digits and print 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 realized a problem that I don’t know how to 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 polynomial with a left -> right direction, and base change polynomials are read in the opposite direction. Due to the use of function getchar() do not know how to finish the exercise. Someone can solve this problem ?

  • What is the problem ? The results do not give correct ? In the quick test I did seemed correct

  • For some numbers the program works, the problem ta in logic the program needs to read from the last to the first, and I can not implement it

  • So some does not work is this ? Can you give an example of one that does not work ? It is difficult to fix anything without seeing an example that is not correct

  • 254 = 11111110, 508 = 111111100, 52 = 110100

  • none of them gives the exact number, because the program reads in this sense --->

1 answer

1


The logic that has works, but reading from the bit of lower weight to the one of higher weight. Which means you have to enter the bits in reverse than normal.

To solve this particular problem and maintain the logic you have, you can first store the bits in an array, and then scroll 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;
}

Check it out at Ideone

It is interesting to mention that it has many ways to do the same conversion, but this is the most similar logic that already had in the code.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.