有计算校验和的解决方案吗?

Is there any solution for calculate checksum?

我正在编写一个 SerialPort 工具,但我遇到了一个问题,我不知道如何计算校验和...

例如:

Flag COMM ID COMM Length Data Remain Sum
0x55 0x00000003 0x0000001c 32bit *3 0x00000000 0xFFFFFFDF

数据:

Remain Sub-Command Remain
0x00000000 0x00000002 0x00000000

计算方法:
校验和,SUM=~((DWORD) COMM ID + (DWORD) COMM Length + (DWORD) Data + (DWORD)Sub-Command + (DWORD) Remain) +1

结果:
55 03 00 00 00 1C 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 DF FF FF FF

如何用 C# 得到总和(如 0xFFFFFFDF)?

你似乎已经或多或少地回答了你自己的问题,尽管你的计算方法同时提到了“数据”和“子命令”,即使“子命令”是部分 “数据”。

int commId = 0x00000003;
int length = 0x0000001c;
int subcommand = 0x00000002;
int remain = 0x00000000;
            
// you said:
// ~((DWORD) COMM ID + (DWORD) COMM Length + (DWORD) Data + (DWORD)Sub-Command + (DWORD) Remain) +1
// you probably wanted Remain + Sub-Command + Remain though,
// as that is what Data is defined as.
int csum = ~(commId + length + remain + subcommand + remain) + 1;
            
Console.WriteLine(csum.ToString("X"));

产生结果 -33,下一个值为 FFFFFFDF

DWORD 只是一个 32 位整数,就像标准 C# int 类型一样。 ~ 是一元否定运算符。