title: CRC-CCITT 16-bit Python Manual Calculation
body: <p><strong>Problem</strong></p>
  
  <p>I am writing code for an embedded device. A lot of solutions out there for CRC-CCITT 16-bit calculations require libraries.</p>
  
  <p>Given that using libraries is almost impossible and a drain on its resources, a function is required.</p>
  
  <p><strong>Possible Solution</strong></p>
  
  <p>The following CRC calculation was found online. However, its implementation is incorrect.</p>
  
  <p><a href="http://bytes.com/topic/python/insights/887357-python-check-crc-frame-crc-16-ccitt" rel="noreferrer">http://bytes.com/topic/python/insights/887357-python-check-crc-frame-crc-16-ccitt</a></p>
  
  <pre><code>def checkCRC(message):
      #CRC-16-CITT poly, the CRC sheme used by ymodem protocol
      poly = 0x11021
      #16bit operation register, initialized to zeros
      reg = 0xFFFF
      #pad the end of the message with the size of the poly
      message += '\x00\x00' 
      #for each bit in the message
      for byte in message:
          mask = 0x80
          while(mask &gt; 0):
              #left shift by one
              reg&lt;&lt;=1
              #input the next bit from the message into the right hand side of the op reg
              if ord(byte) &amp; mask:   
                  reg += 1
              mask&gt;&gt;=1
              #if a one popped out the left of the reg, xor reg w/poly
              if reg &gt; 0xffff:            
                  #eliminate any one that popped out the left
                  reg &amp;= 0xffff           
                  #xor with the poly, this is the remainder
                  reg ^= poly
      return reg
  </code></pre>
  
  <p><strong>Existing Online Solution</strong></p>
  
  <p>The following link calculates a 16 bit CRC correctly.</p>
  
  <p><a href="http://www.lammertbies.nl/comm/info/crc-calculation.html#intr" rel="noreferrer">http://www.lammertbies.nl/comm/info/crc-calculation.html#intr</a></p>
  
  <p>The result under "CRC-CCITT (XModem)" is the correct CRC.</p>
  
  <p><strong>Specification</strong></p>
  
  <p>I believe the "CRC-CCITT (XModem)" calculation in the existing online solution uses a polynomial of <code>0x1021</code>.</p>
  
  <p><strong>Question</strong></p>
  
  <p>If someone could write a new function or provide direction to solve the <code>checkCRC</code> function to the required specification. Please note that the use of libraries or any <code>import</code>'s would not help.</p>