Документ взят из кэша поисковой машины. Адрес оригинального документа : http://www.sao.ru/hq/sts/linux/book/c_marshall/section2_22_15.html
Дата изменения: Unknown
Дата индексирования: Sat Sep 11 20:06:21 2010
Кодировка:

Поисковые слова: md-11
bitcount.c



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