atoi
interprets its input as a decimal number, not a binary number. Your longer string is causing the value to overflow, in which case the return value of atoi
is undefined (although returning INT_MAX
is common, which is equal to the value you're seeing).
To interpret the input as a binary number you can use strtol
like this:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <limits.h>
int main()
{
char line[256];
while (printf("\nInput: "),
fgets(line, sizeof line, stdin))
{
// skip initial whitespace and break if input is nothing but whitespace
char *p = line;
while (isspace(*p)) ++p;
if (*p == '\0') break;
// interpret input as a binary number
long n = strtol(line, &p, 2);
if (p == line)
printf("** Can't convert any characters. **\n");
else if (n == LONG_MAX || n == LONG_MIN)
printf("** Range error **\n");
else
printf("Value: %ld\n", n); // prints value in decimal
while (isspace(*p)) ++p; // skip whitespace after the value
if (*p != '\0')
printf("** Excess characters in input **\n");
}
return 0;
}