我有这个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#中编写此函数?我对^=
运算符的作用感到特别困惑。
答案 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;
}
}