home *** CD-ROM | disk | FTP | other *** search
/ The C Users' Group Library 1994 August / wc-cdrom-cusersgrouplibrary-1994-08.iso / listings / v_11_11 / allison / bit.c next >
C/C++ Source or Header  |  1993-09-01  |  1KB  |  60 lines

  1. LISTING 4 - Implementation File for bit.h
  2. /* bit.c:    Bit operations for unsigned ints */
  3.  
  4. #include <stdio.h>
  5. #include <limits.h>
  6. #include <stdlib.h>
  7. #include <string.h>
  8. #include "bit.h"
  9.  
  10. unsigned fputb(unsigned n, FILE *f)
  11. {
  12.     int i;
  13.     size_t nb = nbits(n);
  14.  
  15.     /* Print the binary form of a number */
  16.     for (i = 0; i < nb; ++i)
  17.         fprintf(f,"%d",test(n,nb-1-i));
  18.     return n;
  19. }
  20.  
  21. unsigned fgetb(FILE *f)
  22. {
  23.     unsigned n = 0;
  24.     size_t nb = nbits(n);
  25.     size_t slen;
  26.     char *buf = malloc(nb+1);
  27.     char format[9];
  28.     int i;
  29.  
  30.     if (buf == NULL)
  31.         return 0;
  32.  
  33.     /* Build read format (e.g., " %16[01]") */
  34.     sprintf(format," %%%d[01]",nb);
  35.     if (fscanf(f,format,buf) != 1)
  36.         return 0;
  37.  
  38.     /* Set corresponding bits in n */
  39.     slen = strlen(buf);
  40.     for (i = 0; i < slen; ++i)
  41.         if (buf[slen-1-i] == '1')
  42.             n = set(n,i);
  43.  
  44.     free(buf);
  45.     return n;
  46. }
  47.  
  48. unsigned count(unsigned n)
  49. {
  50.     unsigned sum = 0;
  51.  
  52.     while (n)
  53.     {
  54.         if (n & 1u)
  55.             ++sum;
  56.         n >>= 1;
  57.     }
  58.     return sum;
  59. }
  60.