title: CRC 16 calculation using python
body: <p>I have an incoming packet that reads 7E0003000204009b387E from a serial port.</p>
  <p>start and end flag is 7E, FCS/CRC is 9b38 and the data is 00030002000400. The FCS is calculated per the algorithm specified in RFC 1662. <a href="https://www.rfc-editor.org/rfc/rfc1662#appendix-A" rel="nofollow noreferrer">https://www.rfc-editor.org/rfc/rfc1662#appendix-A</a></p>
  <p>Can someone provide a way to calculate the crc16 in python.</p>
  <p>here is the C# equivalent of what I am looking for.</p>
  <pre><code>public static class Crc16
  {
      const ushort polynomial = 0x1021;
  
      static readonly ushort[] table = new ushort[256];
  
      public static ushort ComputeChecksum(byte[] bytes)
      {
          ushort crc = 0xffff;
          for (int i = 0; i &lt; bytes.Length; ++i)
          {
              byte index = (byte)(crc ^ bytes[i]);
              crc = (ushort)((crc &gt;&gt; 8) ^ table[index]);
          }
          return (ushort)~crc;
      }
  
      static Crc16()
      {
          ushort value;
          ushort temp;
          for (ushort i = 0; i &lt; table.Length; ++i)
          {
              value = 0;
              temp = i;
              for (byte j = 0; j &lt; 8; ++j)
              {
                  if (((value ^ temp) &amp; 0x0001) != 0)
                  {
                      value = (ushort)((value &gt;&gt; 1) ^ polynomial);
                  }
                  else
                  {
                      value &gt;&gt;= 1;
                  }
                  temp &gt;&gt;= 1;
              }
              table[i] = value;
          }
      }
  }
  </code></pre>