home *** CD-ROM | disk | FTP | other *** search
/ Graphics Plus / Graphics Plus.iso / general / procssng / ccs / ccs-11tl.lha / lbl / sun / lib2 / checksum.c < prev    next >
Encoding:
Text File  |  1993-06-09  |  761 b   |  36 lines

  1. /*
  2. @    C H E C K S U M . C
  3. @
  4. @ Checksum routine for Internet Protocol family headers (C Version)
  5. @
  6. */
  7. checksum(buf, len)
  8. register unsigned short*    buf;
  9. register int    len;
  10. {
  11. register int    sum = 0;
  12.  
  13.     /*
  14.      *  Our algorithm is simple, using a 32 bit accumulator (sum),
  15.      *  we add sequential 16 bit words to it, and at the end, fold
  16.      *  back all the carry bits from the top 16 bits into the lower
  17.      *  16 bits.
  18.      */
  19.     while (len > 1)  {
  20.         sum += *buf++;
  21.         len -= 2;
  22.     }
  23.  
  24.     /* mop up an odd byte, if necessary */
  25.     if(len == 1)
  26.         sum += *(unsigned char *)buf;
  27.  
  28.     /*
  29.      * add back carry outs from top 16 bits to low 16 bits
  30.      */
  31.     sum = (sum >> 16) + (sum & 0xffff);    /* add hi 16 to low 16 */
  32.     sum += (sum >> 16);            /* add carry */
  33.     return    ~sum;                /* truncate to 16 bits */
  34. }
  35.  
  36.