/* * print a number as a sequence of bits * * example program with a bug in it * * Matt Bishop, ECS 36A, Fall 2019 */ #include /* * macros */ #define MAXLINE 1000 /* maximum input line length */ /* * print the bits in an integer */ void prbits(unsigned int x) { int i; /* counter in a for loop */ int bit; /* the bit */ int nbits = sizeof(unsigned int) * 8; /* how many bit in an unsigned int */ /* * loop through the (computer) word, putting out 1 bit at a time */ for(i = 0; i < nbits; i++){ /* extract ith bit */ bit = (x>>i)&01; /* print it, visibly */ printf("%c", bit); } /* done -- end of line to finish it up */ putchar('\n'); } /* * main routine */ int main(int argc, char *argv[]) { char buf[MAXLINE]; /* input buffer */ int num; /* prompt for input */ printf("> "); /* * loop until no more input */ while(fgets(buf, MAXLINE, stdin) != NULL){ /* translate input into an integer */ if (sscanf(buf, "%d", &num) != 1){ fprintf(stderr, "%s: not a valid integer\n", buf); continue; } /* print the bits out */ prbits((unsigned int) num); /* reprompt */ printf("> "); } /* bye! */ return(0); }