Sample CRC Code

    The following sample code represents a practical implementation ofthe CRC (Cyclic Redundancy Check). (See also ISO 3309 and ITU-T V.42 for a formal specification.)

    The sample code is in the ANSI C programming language. Non C users may find it easier to read with these hints:

   &      Bitwise AND operator.
   ^      Bitwise exclusive-OR operator.
   >>     Bitwise right shift operator. When applied to an
          unsigned quantity, as here, right shift inserts zero
          bit(s) at the left.
   !      Logical NOT operator.
   ++     "n++" increments the variable n.
   0xNNN  0x introduces a hexadecimal (base 16) constant.
          Suffix L indicates a long value (at least 32 bits).

   /**//* Table of CRCs of all 8-bit messages. */
   unsigned long crc_table[256];

   /**//* Flag: has the table been computed? Initially false. */
   int crc_table_computed = 0;

   /**//* Make the table for a fast CRC. */
   void make_crc_table(void)
   {
     unsigned long c;

     int n, k;
     for (n = 0; n < 256; n++) {
       c = (unsigned long) n;
       for (k = 0; k < 8; k++) {
         if (c & 1) {
           c = 0xedb88320L ^ (c >> 1);
         } else {
           c = c >> 1;
         }
       }
       crc_table[n] = c;
     }
     crc_table_computed = 1;
   }

   /**//*
      Update a running crc with the bytes buf[0..len-1] and return
    the updated crc. The crc should be initialized to zero. Pre- and
    post-conditioning (one's complement) is performed within this
    function so it shouldn't be done by the caller. Usage example:

      unsigned long crc = 0L;

      while (read_buffer(buffer, length) != EOF) {
        crc = update_crc(crc, buffer, length);
      }
      if (crc != original_crc) error();
   */
   unsigned long update_crc(unsigned long crc,
                   unsigned char *buf, int len)
   {
     unsigned long c = crc ^ 0xffffffffL;
     int n;

     if (!crc_table_computed)
       make_crc_table();
     for (n = 0; n < len; n++) {
       c = crc_table[(c ^ buf[n]) & 0xff] ^ (c >> 8);
     }
     return c ^ 0xffffffffL;
   }

   /**//* Return the CRC of the bytes buf[0..len-1]. */
   unsigned long crc(unsigned char *buf, int len)
   {
     return update_crc(0L, buf, len);
   }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值