title: C - reading binary file, validating checksum
body: <p>In C, what would be a proper way to read the contents of a binary file and validate the checksum?</p>
  
  <p>Here is a sample of the data I'm working with:</p>
  
  <pre>
  0A 01 17 D8 04 00 07 9A 1F 10 FF CF 7F FF FF FF
  FF 7F 7F 7F FF 7F FF FF FF FF 7F 81 01 01 03 01
  01 01 01 81 00 73 67 68 66 97 6C 76 64 64 6A 6B
  6E 64 66 67 44 41 [17 7A]</pre>
  
  <p>and</p>
  
  <pre>
  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  00 00 00 00 44 41 [00 85]</pre>
  
  <p>The checksum (between square brackets) stores the sum of the previous 54 bytes as a 2-byte (big-endian) number.</p>
  
  <p>This is what I've been using:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  int main(int argc, char **argv)
  {
      FILE *f = fopen(argv[1], "rb");
  
      unsigned char data[512];
      fread(data, 1, 512, f);
  
      int i;
      int sum = 0;
      for (i = 0; i &lt; 54; i++)
      {
          sum += data[i];
      }
  
      if ((sum &gt;&gt; 8)   == data[54] &amp;&amp;
          (sum &amp; 0xFF) == data[55])
      {
          printf("Checksum is valid.\n");
      }
      else
      {
          printf("Checksum is invalid.\n");
      }
      system("pause");
  }
  </code></pre>
  
  <p>I have used a char array to store the bytes, using the indexes to recalculate the checksum in a loop. To validate I used some bitwise shifting and masking. Is there a better solution?</p>
  
  <p>Thanks!</p>