将 Arduino 校验和函数转换为 C#
Convert Arduino checksum-function to C#
我有这个 Arduino 校验和函数,我想在 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# 中编写此函数?我特别困惑 ^=
运算符的作用。
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;
}
}
我有这个 Arduino 校验和函数,我想在 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# 中编写此函数?我特别困惑 ^=
运算符的作用。
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;
}
}