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?