Next: lowio.c Up: Program Listings Previous: queue.c

bitcount.c


/* binary counting exampple -counts bits set to 1 in an 8 bit number */


/* acc -o bitcount bitcount.c on SUNS */

/* c89 -o bitcount bitcount.c on DECS */

#include <stdio.h>

unsigned char bitcount(unsigned char); /* prototype */

main()

{  unsigned char i8,count;
   int i;

   printf("Enter number (0 - 255 decimal)\n");
   scanf("%d",&i);
   
   if (( i < 0 ) || (i > 255))
     { printf("Error:Number out of range = %d\n", i);
       exit(1);
     }
  
   i8 = (unsigned char) i;
   
   count = bitcount(i8);
   
   printf("\n\nNumber of bits set to 1 in %d = %d\n",i,count);
   
}

unsigned char bitcount(unsigned char x)

{  unsigned char count;


   for (count = 0; x!=0; x>>=1)
     if ( x & 01 )
       ++count;
       
   return count;
}


Dave.Marshall@cm.cf.ac.uk
Wed Sep 14 10:06:31 BST 1994