title: How to calculate crc8 in C?
body: <p>I have seen multiple implementation of crc8 implementation in C, but I am unable to figure out for polynomial(x8,x5,x4,1) i.e. <code>0x31</code> and initialization <code>0xFF</code>. </p>
  
  <p>Also reflect input = False, reflect output = False and final XOR = <code>0x00</code>. </p>
  
  <p>I tried several of them, and I expect such that <code>CRC(0x00)=0xAC</code> and <code>CRC(0xBEEF)=0x92</code>.</p>
  
  <p>I have seen similar implementations, but nothing really worked out. I saw the exact functionality in here <a href="http://www.sunshine2k.de/coding/javascript/crc/crc_js.html" rel="noreferrer">http://www.sunshine2k.de/coding/javascript/crc/crc_js.html</a> where I could give initialization, reflect input, reflect output, and final XOR. But can somebody point to me implementation in C. I do understand that initially we need to give crc as 0xFF, but nothing worked out for me so far.</p>
  
  <p>Please find the sample code that I tried attached:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdint.h&gt;
  
  uint8_t crc8(uint16_t input);
  
  int main()
  {
      uint8_t temp1;
      uint16_t temp2 = 0xBEEF;
  
      printf("CRC input is 0x%X\n", temp2);
  
      temp1 = crc8(temp2);
  
      printf("CRC output is 0x%X\n", temp1);
  
      return 0;
  }
  
  uint8_t crc8(uint16_t input)
  {
      uint8_t crc[8] = { };
      uint8_t i;
      uint8_t inv;
      uint8_t output = 0;
  
      for(i = 0; i &lt; 16; i++)
      {
          inv = ((((input &gt;&gt; i) &amp; 1) ^ crc[7]) &amp; 1);
  
          crc[7] = (crc[6] &amp; 1);
          crc[6] = (crc[5] &amp; 1);
          crc[5] = (crc[4] ^ inv &amp; 1);
          crc[4] = (crc[3] ^ inv &amp; 1);
          crc[3] = (crc[2] &amp; 1);
          crc[2] = (crc[1] &amp; 1);
          crc[1] = (crc[0] &amp; 1);
          crc[0] = (inv &amp; 1);
      }
  
      for(i = 0; i &lt; 8; i++){
          output |= ((crc[i] &lt;&lt; i) &amp; (1 &lt;&lt; i));
      }
  
  
      return output;
  }
  </code></pre>
  
  <p>I am seeing </p>
  
  <pre><code>CRC input is 0xBEEF
  CRC output is 0x2 //instead of 0x92
  </code></pre>