[Checksum] get XOR Arduino

This code written in C# calculates a simple checksum. You can use this to either verify a checksum or calculate one to append to your string. I have used this checksum for Arduino-to-C# communication since it was not stable enough.

You can use this code for either decoding and checking for instance GPS information (GPGGA for example) , or make your own checksum and append it to a string.

The idea is that your sentence has the form:
$$blablablabla*
then it will append the checksum (two chars) behind this *. Then you should just past a nr behind the sentence.

  1.  // Calculates the checksum for a line
  2.         public string GetXORChecksum(string sentence)
  3.         {
  4.             // Go thourgh characters
  5.             int Checksum = 0;
  6.             foreach (char Character in sentence)
  7.             {
  8.                 if (Character == '$')
  9.                 {
  10.                 }
  11.                 else if (Character == '*')
  12.                 {
  13.                     break;
  14.                 }
  15.                 else
  16.                 {
  17.                     if (Checksum == 0)
  18.                     {
  19.                         Checksum = Convert.ToByte(Character);
  20.                     }
  21.                     else
  22.                     {
  23.                         Checksum = Checksum ^ Convert.ToByte(Character);
  24.                     }
  25.                 }
  26.             }
  27.             // Return the result (checksum)
  28.             return Checksum.ToString("X2");
  29.         }

Tim Zaman

MSc Biorobotics. Specialization in computer vision and deep learning. Works at NVIDIA.

You may also like...