home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / snipps97.zip / PARITY.C < prev    next >
C/C++ Source or Header  |  1997-07-04  |  1KB  |  65 lines

  1. /* +++Date last modified: 05-Jul-1997 */
  2.  
  3. /*
  4. **  PARITY.C - Computes even or odd parity for various integral types
  5. **
  6. **  public domain demo by Bob Stout
  7. */
  8.  
  9. #include "parity.h"
  10.  
  11. unsigned parity32(unsigned long x, Parity_T even)
  12. {
  13.       x = x ^ (x >> 16);
  14.       x = x ^ (x >> 8);
  15.       x = x ^ (x >> 4);
  16.       x = x ^ (x >> 2);
  17.       x = x ^ (x >> 1);
  18.  
  19.       return ((unsigned)(x & 1)) ^ even;
  20. }
  21.  
  22. unsigned parity16(unsigned short x, Parity_T even)
  23. {
  24.       x = x ^ (x >> 8);
  25.       x = x ^ (x >> 4);
  26.       x = x ^ (x >> 2);
  27.       x = x ^ (x >> 1);
  28.  
  29.       return ((unsigned)(x & 1)) ^ even;
  30. }
  31.  
  32. unsigned parity8(unsigned char x, Parity_T even)
  33. {
  34.       x = x ^ (x >> 4);
  35.       x = x ^ (x >> 2);
  36.       x = x ^ (x >> 1);
  37.  
  38.       return ((unsigned)(x & 1)) ^ even;
  39. }
  40.  
  41. unsigned parity64(void *x, Parity_T even)
  42. {
  43.       union longlong *val64 = (union longlong *)x;
  44.  
  45.       return (parity32(val64->lo, even) ^ parity32(val64->hi, even));
  46. }
  47.  
  48. #ifdef TEST
  49.  
  50. #include <stdio.h>
  51. #include <stdlib.h>
  52.  
  53. main(int argc, char *argv[])
  54. {
  55.       while (--argc)
  56.       {
  57.             unsigned long n = strtoul(*(++argv), NULL, 10);
  58.  
  59.             printf("Even parity of %ld = %d\n", n, parity32(n, Even_));
  60.             printf("Odd parity of  %ld = %d\n\n", n, parity32(n, Odd_));
  61.       }
  62. }
  63.  
  64. #endif
  65.