title: How can I convert C++ code of a CRC16-CCITT algorithm to Python code?
body: <p>I have an example code for CRC16-CCITT algorithm written in C++ and I need help converting it to Python.  </p>
  
  <p>Example C++ code:</p>
  
  <pre><code>#include&lt;iostream&gt;
  
  using namespace std;
  
  unsigned short calculateCRC(unsigned char data[], unsigned int length)
  {
          unsigned int i;
          unsigned short crc = 0;
  
          for(i=0; i&lt;length; i++){
                  crc = (unsigned char)(crc &gt;&gt;8) | (crc&lt;&lt;8);
                  crc ^= data[i];
                  crc ^= (unsigned char)(crc &amp; 0xff) &gt;&gt; 4;
                  crc ^= crc &lt;&lt; 12;
                  crc ^= (crc &amp; 0x00ff) &lt;&lt; 5;
          }
  
          return crc;
  }
  
  int main()
  {
          unsigned int length;
          length = 15;
  
          unsigned char data[length] = {0x01,0x08,0x00,0x93,0x50,0x2e,0x42,0x83,0x3e,0xf1,0x3f,0x48,0xb5,0x04,0xbb};
          unsigned int crc;
          crc =  calculateCRC(data, length);
          cout&lt;&lt; std::hex &lt;&lt; crc &lt;&lt; '\n';
  }
  </code></pre>
  
  <p>This code gives 9288 as output which is correct.</p>
  
  <p>I tried the following in Python: </p>
  
  <pre><code>#!/usr/bin/env python3
  
  def calculateCRC(data):
      crc = 0
  
      for dat in data:
          crc = (crc &gt;&gt; 8) or (crc &lt;&lt; 8)
          crc ^= dat
          crc ^= (crc and 0xff) &gt;&gt; 4
          crc ^= crc &lt;&lt; 12
          crc ^= (crc and 0x00ff) &lt;&lt; 5
      crc = hex(crc)
      return (crc)
  
  
  data = [0x01,0x08,0x00,0x93,0x50,0x2e,0x42,0x83,0x3e,0xf1,0x3f,0x48,0xb5,0x04,0xbb]
  print(calculateCRC(data))
  </code></pre>
  
  <p>This outputs 0xf988334b0799be2081. </p>
  
  <p>Could you please help me understand what I am doing wrong?
  Thank you.</p>