简体   繁体   中英

Convert Arduino checksum-function to C#

I've got this Arduino-checksum function I'd like to use in C# to check the validity of the data I received:

char s in Arduino are 1 byte long, int s take two bytes, the corresponding data-type in C# is short

char Send::calcChecksum(const char* const packet, const int packetLength) {
    int i = 0;
    char checksum = 0;
    while(i < packetLength) {
        checksum ^= packet[i++];
    }
    return checksum;
}

How would I write this function in C# ? I'm especially confused what the ^= operator does.

using System;

public class Program
{
    public static void Main()
    {
        var stringToCheck = "hi there";

        Console.WriteLine("Checksum for " + stringToCheck + ": " + CalcChecksum(stringToCheck, stringToCheck.Length));
    }

    static int CalcChecksum(string packet, int packetLength)
    {
        char checksum = (char)0;

        for (int i = 0; i < packetLength; i++)
        {
            checksum ^= packet[i];
        }

        return checksum;
    }
}

https://dotnetfiddle.net/6icpvv

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM