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
– Isac
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
– vitor bernardo
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
– Isac
254 = 11111110, 508 = 111111100, 52 = 110100
– vitor bernardo
none of them gives the exact number, because the program reads in this sense --->
– vitor bernardo