bits3.c

/*
 * print a number as a sequence of bits
 *
 * example program with a bug in it
 *
 * Matt Bishop, ECS 36A, Fall 2019
 * -- May 21, 2024      Modified to fix some warnings
 */
#include <stdio.h>


/*
 * 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>>((nbits-1)-i))&01;
		/* print it, visibly */
		printf("%c", bit+'0');
	}

	/* done -- end of line to finish it up */
	putchar('\n');
}

/*
 * main routine
 */
int main(void)
{
	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);
}



UC Davis sigil
Matt Bishop
Office: 2209 Watershed Sciences
Phone: +1 (530) 752-8060
Email: [email protected]
ECS 36A, Programming & Problem Solving
Version of April 2, 2024 at 12:13PM

You can get the raw source code here.

Valid HTML 4.01 Transitional Built with BBEdit Built on a Macintosh