title: CRC 16 in matlab
body: <p>i actually want to generate crc in matlab for Modbus protocol and i have used following code in matlab. I have also given message array as <code>message=uint16([hex2dec('01') hex2dec('02') hex2dec('00') hex2dec('C4') hex2dec('00') hex2dec('16')]);</code> and done bitand with 0xffff at the end, but it is  unable to give correct crc.. </p>
  
  <p>My code is as below and the expected crc is <strong>B839</strong> as per the Modbus crc calculator but it is giving <strong>B8DD</strong>(47325 decimal). Please help me if there is anything to change in the code. Thank you.</p>
  
  <pre><code>function crc_val = crc3 (~)
  crc = uint16(hex2dec('1D0F'));  % Non-augmented initial value equivalent to augmented initial value 0xFFFF
  polynomial = hex2dec('1021'); % Polynomial
  message=uint16([hex2dec('01') hex2dec('02') hex2dec('00') hex2dec('C4') hex2dec('00') hex2dec('16') hex2dec('00') hex2dec('00')]);
  for i = 1:(length(message)-2) % Not taking the last 2 bytes because they are the CRC.
      crc = bitxor(crc, bitsll(message(i), 8));
      for j = 1:8
          if (bitand(crc, hex2dec('8000')) &gt; 0);
              crc = bitxor(bitsll(crc, 1), polynomial);
          else
              crc = bitsll(crc, 1);
          end
      end
  end
  crc_val = bitand(crc, hex2dec('ffff'));
  
  end
  </code></pre>