将Arduino校验和函数转换为C#
本文关键字:转换 函数 Arduino 校验和 | 更新日期: 2023-09-27 18:01:09
我有一个Arduino校验和函数,我想在C#中使用它来检查我收到的数据的有效性:
Arduino中的char
s为1字节长,int
s为2字节,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#中编写此函数我特别困惑^=
运算符的作用。
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