Search code examples
c#serial-portrangechecksummodulo

Problems with checksum modulo 256 C#


I am a student industrial engineering in the field of electrotechnics. I am not used to work with c#. I am trying to make a checksum tha consists of 2 bytes. The checksum is computed with the following algorithm:

A = 0xFF 
B = 0 

For I FROM 0 TO number_of_bytes -1 DO 
   A := (A + DATA[I]) mod 0x100; 
   B := (B + A) mod 0x100; 
END 

checksum[0] := A 
checksum[1] := B

A and B are byte values and the addition is made modulo 256.

When i run the program it breaks at A += byteToCalculate[i]; This warning occures:

"An exception of type 'System.IndexOutOfRangeException' occurred in communicatie.exe but was not handled in user code."

Can someone help me with this problem?

    public void ChecksumBerekenen(object sender, EventArgs e)
    {

        byte[] byteToCalculate = new byte[] { 0x00, 0x02, 0x02, 0x00, 0x58, 0x04, 0x00, 0x00, 0x05, 0x00, bytewaarde_2[3], bytewaarde_2[2], bytewaarde_2[1], bytewaarde_2[0] };

        int A = 0xff;
        int B = 0;

        for (int i = 0; i <= byteToCalculate.Length ; i++)
        {
            A += byteToCalculate[i];
            A %= 0x100;

            B += A ;
            B %= 0x100;
        }
        VerstuurdeData.AppendText(A.ToString("x") + " " + B.ToString("x"));
    }

Solution

  • In order to avoid such pesky errors (<= instead of required <) use foreach loop:

      foreach (var item in byteToCalculate) {
        A += item;
        A %= 0x100;
    
        B += A;
        B %= 0x100;
      }
    

    and you'll have a more readable code as a bonus.