将Arduino校验和函数转换为C#

时间:2015-07-06 12:54:52

标签: c# c++ arduino checksum

我有这个Arduino-checksum函数我想在C#中用来检查我收到的数据的有效性:

Arduino中的

char长度为1个字节,int取两个字节,C#中相应的数据类型为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;
}

我如何在C#中编写此函数?我对^=运算符的作用感到特别困惑。

1 个答案:

答案 0 :(得分:1)

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