title: Java equivalent for C CRC16
body: <p>I need to convert <code>C</code> CRC16 method to <code>Java</code>. The problem is I'm not that good with <code>C</code> and Bytes operations.</p>
  
  <p><code>C</code> code:</p>
  
  <pre><code>static const unsigned short crc16_table[256] =
  {
   0x0000,0xC0C1,0xC181,0x0140,0xC301,0x03C0,0x0280,0xC241,
   ...  /* Removed for brevity */
   0x8201,0x42C0,0x4380,0x8341,0x4100,0x81C1,0x8081,0x4040
  };
  
  unsigned short crc16 (const void *data, unsigned data_size)
  {
   if (!data || !data_size)
   return 0;
   unsigned short crc = 0;
   unsigned char* buf = (unsigned char*)data;
   while (data_size--)
   crc = (crc &gt;&gt; 8) ^ crc16_table[(unsigned char)crc ^ *buf++];
   return crc;
  }
  </code></pre>
  
  <p>And that's my attempt to convert it. Not sure if that's correct.</p>
  
  <pre><code>private static int[] table = {
      0x0000,0xC0C1,0xC181,0x0140,0xC301,0x03C0,0x0280,0xC241,0xC601,0x06C0,0x0780,0xC741,
      ...    // Removed for brevity
      0x4400,0x84C1,0x8581,0x4540,0x8701,0x47C0,0x4680,0x8641,0x8201,0x42C0,0x4380,0x8341, 0x4100,0x81C1,0x8081,0x4040
  };
  
  public static int getCode (String[] data){
      if (data.length == 0) {
          return 0;
      }
      int crc = 0;
      for (String item : data) {
          byte[] bytes = item.getBytes();
          for (byte b : bytes) {
              crc = (crc &gt;&gt;&gt; 8) ^ table[(crc ^ b) &amp; 0xff]; //this confuses me
          }
      }
      return crc;
  }
  </code></pre>
  
  <p><strong>Question:</strong>
  Is my porting to Java correct?</p>
  
  <hr>
  
  <p><strong>EDIT</strong>:</p>
  
  <p>Modified <code>crc16</code> working method (thanks to great answers):</p>
  
  <pre><code>public static int getCode(String data) {
      if (data == null || data.equals("")) {
          return 0;
      }
      int crc = 0x0000;
      byte[] bytes = data.getBytes();
      for (byte b : bytes) {
          crc = (crc &gt;&gt;&gt; 8) ^ table[(crc ^ b) &amp; 0xff];
      }
      return crc;
  }
  </code></pre>
  
  <p>This returns Decimal value. And CRC16 code needs to be Hexadecimal. I used this method to convert to base 16. Do it with received <code>crc</code> like <code>dec2m(crc, 16)</code>:</p>
  
  <pre><code>static String dec2m(int N, int m) {
      String s = "";
      for (int n = N; n &gt; 0; n /= m) {
          int r = n % m;
          s = r &lt; 10 ? r + s : (char) ('A' - 10 + r) + s;
      }
      return s;
  }
  </code></pre>
  
  <p>For testing your results you could use <a href="http://www.lammertbies.nl/comm/info/crc-calculation.html" rel="nofollow">this site</a> (Thanks to @greenaps)</p>