Listing 5 fgetb skips initial whitespace and returns a binary number from a given input stream.

#include <stdio.h>
#include <string.h>

#define BUFSIZE 64
#define MAXBITS 15     /* Largest value allowed is 32767 */

int fgetb(FILE *fp)
{
    int i;
    unsigned sum = 0, value = 1;
    char buf[BUFSIZE];

    if (!fp || fscanf(fp," %[01]",buf) != 1 ||
      strlen(buf) > MAXBITS)
        return EOF;
    for (i = strlen(buf) - 1; i >= 0; --i)
    {
        if (buf[i] == '1')
           sum += value;
        value *= 2;
    }
    return sum;
}

main()
{
    int n = fgetb(stdin);
    printf("The number was %d\n",n);
    return 0;
}
/* End of File */