unsigned.c

#include <stdio.h>

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

/*
 * print the bits in an integer
 */
void prsbits(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-i))&01;
                /* print it, visibly */
                printf("%c", bit+'0');
        }
}

int main(void)
{
	int i = -53;
	unsigned int u;

	printf("As a signed number, -53 is %d\n", i);
	printf("And as bits: "); prsbits(i); printf("\n");
	u = (unsigned) i;
	printf("As an unsigned number, -53 is %u\n", u);
	printf("And as bits: "); prbits(i); printf("\n");


	return(0);
}


UC Davis sigil
Matt Bishop
Office: 2209 Watershed Sciences
Phone: +1 (530) 752-8060
Email: mabishop@ucdavis.edu
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