title: Bitwise operator to calculate checksum
body: <p>Am trying to come up with a C/C++ function to calculate the checksum of a given array of hex values.</p>
  
  <p>char *hex = "3133455D332015550F23315D";</p>
  
  <p>For e.g., the above buffer has 12 bytes and then last byte is the checksum.</p>
  
  <p>Now what needs to done is, convert the 1st 11 individual bytes to decimal and then take there sum.</p>
  
  <p>i.e., 31 = 49, 
        33 = 51,.....</p>
  
  <p>So 49 + 51 + .....................</p>
  
  <p>And then convert this decimal value to Hex. And then take the LSB of that hex value and convert that to binary.</p>
  
  <p>Now take the 2's complement of this binary value and convert that to hex. At this step, the hex value should be equal to 12th byte.</p>
  
  <p>But the above buffer is just an example and so it may not be correct.</p>
  
  <p>So there're multiple steps involved in this. </p>
  
  <p>Am looking for an easy way to do this using bitwise operators. </p>
  
  <p>I did something like this, but it seems to take the 1st 2 bytes and doesn't give me the right answer.</p>
  
  <pre><code>int checksum (char * buffer, int size){
      int value = 0;
      unsigned short tempChecksum = 0;
      int checkSum = 0;
  
      for (int index = 0; index &lt; size - 1; index++) {
          value = (buffer[index] &lt;&lt; 8) | (buffer[index]);
          tempChecksum += (unsigned short) (value &amp; 0xFFFF);
       }
  
        checkSum = (~(tempChecksum &amp; 0xFFFF) + 1) &amp; 0xFFFF;  
  }
  </code></pre>
  
  <p>I couldn't get this logic to work. I don't have enough embedded programming behind me to understand the bitwise operators. Any help is welcome.</p>
  
  <p><strong>ANSWER</strong></p>
  
  <p>I got this working with below changes.</p>
  
  <pre><code>for (int index = 0; index &lt; size - 1; index++) {
              value = buffer[index];
              tempChecksum += (unsigned short) (value &amp; 0xFFFF);
           }
      checkSum = (~(tempChecksum &amp; 0xFF) + 1) &amp; 0xFF;
  </code></pre>