title: Why is the calculated checksum not matching the BCC sent over the serial port?
body: <p>I've got a little application written in C# that listens on a SerialPort for information to come in.  The information comes in as: <code>STX + data + ETX + BCC</code>.  We then calculate the BCC of the transmission packet and compare.  The function is:</p>
  
  <pre><code>private bool ConsistencyCheck(byte[] buffer)
  {
      byte expected = buffer[buffer.Length - 1];
      byte actual = 0x00;
  
      for (int i = 1; i &lt; buffer.Length - 1; i++)
      {
          actual ^= buffer[i];
      }
  
      if ((expected &amp; 0xFF) != (actual &amp; 0xFF))
      {
          if (AppTools.Logger.IsDebugEnabled)
          {
              AppTools.Logger.Warn(String.Format("ConsistencyCheck failed: Expected: #{0} Got: #{1}", expected, actual));
          }
      }
  
      return (expected &amp; 0xFF) == (actual &amp; 0xFF);
  }
  </code></pre>
  
  <p>And it seems to work more or less.  It is accurately not including the STX or the BCC and accurately including the ETX in it's calculations.  It seems to work a very large percentage of the time, however we have at least two machines we are running this on, both of which are Windows 2008 64-bit in which the BCC calculation NEVER adds up.  Pulling from a recent log I had in one byte 20 was sent and I calculated 16 and one where 11 was sent and I calculated 27.</p>
  
  <p>I'm absolutely stumped as to what is going on here.  Is there perhaps a 64 bit or Windows 2008 "gotcha" I'm missing here?  Any help or even wild ideas would be appreciated.</p>
  
  <p>EDIT:</p>
  
  <p>Here's the code that reads the data in:</p>
  
  <pre><code>private void port_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
  {
      // Retrieve number of bytes in the buffer
      int bytes = serialPort.BytesToRead;
  
      // Create a byte array to hold the awaiting data
      byte[] received = new byte[bytes];
  
      //read the data and store it
      serialPort.Read(received, 0, bytes);
  
      DataReceived(received);
  }
  </code></pre>
  
  <p>And the <code>DataReceived()</code> function takes that string and appends it to global <code>StringBuilder</code> object.  It then stays as a string builder until it's passed to these various functions at which point the <code>.ToString()</code> is called on it.</p>
  
  <p>EDIT2: Changed the code to reflect my altered routines that operate on bytes/byte arrays rather than strings.</p>
  
  <p>EDIT3: I still haven't figured this out yet, and I've gotten more test data that has completely inconsistent results (the amount I'm off of the send checksum varies each time with no pattern).  It feels like I'm just calculating the checksum wrong, but I don't know how.</p>