title: Function to Calculate a CRC16 Checksum
body: <p>I'm working on a library to provide simple reliable communication over an RS232 or RS485 connection.  Part of this code involves using a CRC16 checksum on the data to detect corruption from line noise.  I've created a function to calculate a CRC16 checksum, but it doesn't seem to be outputting correct values.</p>
  
  <p>The relevant code I've written is below (it can also be found <a href="https://gist.github.com/2666368" rel="noreferrer">here</a>).</p>
  
  <pre><code>#include &lt;stdint.h&gt;
  
  #define CRC16 0x8005
  
  uint16_t gen_crc16(const uint8_t *data, uint16_t size)
  {
      uint16_t out = 0;
      int bits_read = 0, bit_flag;
  
      /* Sanity check: */
      if(data == NULL)
          return 0;
  
      while(size &gt; 0)
      {
          bit_flag = out &gt;&gt; 15;
  
          /* Get next bit: */
          out &lt;&lt;= 1;
          out |= (*data &gt;&gt; (7 - bits_read)) &amp; 1;
  
          /* Increment bit counter: */
          bits_read++;
          if(bits_read &gt; 7)
          {
              bits_read = 0;
              data++;
              size--;
          }
  
          /* Cycle check: */
          if(bit_flag)
              out ^= CRC16;
      }
  
      return out;
  }
  </code></pre>
  
  <p>I'm checking my output against <a href="http://www.lammertbies.nl/comm/info/crc-calculation.html" rel="noreferrer">this online CRC calculator</a>.</p>
  
  <p>I've come to the conclusion that either my understanding of how to calculate a CRC16 is wrong, or the online calculator is wrong (the former seems more likely).  Can someone tell me where I might be going wrong?</p>